简体   繁体   中英

Does this cause undefined behavior?

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. 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()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM