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.