Is is safe to pass a function parameter like getAName(getA().get())
? getA()
return a object unique_ptr<A>
.
I test with the whole code below on VS 2010, it works. But I would like to make sure if it's c++ standard, is it safe with other c++ compilers?
#include "stdafx.h"
#include <memory>
#include <iostream>
using namespace std;
class A
{
public:
A(){ cout<<"A()"<<endl;}
~A(){ cout<<"~A()"<<endl;}
string name() { return "A"; }
};
std::unique_ptr<A> getA()
{
return std::unique_ptr<A>(new A());;
}
void getAName(A* a)
{
if(a)
{
cout << a->name().c_str() << endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
getAName(getA().get());
return 0;
}
The outputs in console are:
A()
A
~()
Is it necessary to make code as below for safe for all compilers?
unique_ptr<A> a = getA();
getAName(a.get());
It is safe. getA()
returns a temporary std::unique_ptr
, which will be destroyed after the full expression, which constains the invocation of getAName()
. So inside the body of getAName()
the pointer passed remains valid.
All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created, ...
Note that if the pointer passed in is stored somewhere (e.g. a global variable) and then used later (i.e. after the invocation of getAName()
), the object pointed by the pointer has been destroyed by the temporary std::unique_ptr
and the pointer becomes dangled; then deference on it would be UB. If this is the case, as you showed, you might need a named variable for it.