Avoiding undefined behaviour: passing a temporary to a `std::function` which has a const ref member variable
This example has no undefined behavior.
Calling Store
copy-initializes the argument of type std::function<void()>
from the temporary object of type B
. In doing so, std::function
uses perfect forwarding to initialize its own internal object of type B
, which is therefore move-constructed from the original temporary.
The call to emplace_back
copy-constructs the function which therefore copy-constructs the internal object of type B
.
That the initial B
object is a temporary is irrelevant, as the copy inside the function inside the vector is not. The reference to A
inside this B
copy still points to the same A
object, which is still within its lifetime.