When we pass an object which is managed by temporary smart pointer to a function by raw pointer or by reference, does the standard guarantee that the object's lifetime will extend to the function lifetime?
#include <iostream>
#include <memory>
struct A {
~A() {
std::cout << "~A()" << std::endl;
}
};
std::unique_ptr<A> makeA() {
return std::make_unique<A>();
}
void f(const A& a) {
std::cout << "f()" << std::endl;
}
int main() {
f(*makeA());
return 0;
}
I would expect that the instance of A managed by unique_ptr is destroyed once the raw pointer is obtained from it, as it is a temporary and it is not bound to function arguments. So the output could be
~A()
f()
But both gcc and clang make it live till the function ends, i.e. the output is
f()
~A()
So it seems that the temporary smart pointer is not destroyed.
Why does the A instance (located in the heap) live till the function end? Some reference to the standard is highly appreciated.
Temporaries live until the end of the full-expression in which they were created (with some life time extension exceptions), see [class.temporary]/4.
In your case the temporary of interest of type std::unique_ptr<A> is created by makeA() and the full-expression this is a subexpression of is f(*makeA());, so the temporary's life time will end at that semicolon.
The object that the unique_ptr manages is also destroyed only when the unique_ptr itself is destroyed (that is the purpose of the smart pointer).
For exceptions to that rule, see the following paragraph of the standard.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With