Address sanitizer is complaining.
struct X
{
iterator begin();
iterator end();
};
X foo();
const X& bar(const X& x)
{
return x;
}
BOOST_FOREACH(const auto& xitem, bar(foo()))
{
//use xitem
}
Address sanitizer is complaining.
struct X
{
iterator begin();
iterator end();
};
X foo();
const X& bar(const X& x)
{
return x;
}
BOOST_FOREACH(const auto& xitem, bar(foo()))
{
//use xitem
}
Yes, this causes undefined behavior.
When you bind a const reference to a temporary, the lifetime of the temporary is extended to the scope of the bound reference. In your case, this is the function bar
. Thus, you cannot access the temporary after the bar
function exits.
Edit:
Looked it up in the standard and actually the lifetime of the temporary is extended to the full expression containing bar
. So it depends on how BOOST_FOREACH
is implemented whether your code is UB or not.
From N3337 12.2.5
A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full expression containing the call.
Yes. The FOREACH is happening on a reference to a struct which has been created by the foo call, and gone out of scope after being passed through to bar()