C++:将 unique_ptr::get() 之类的参数传递给函数是否安全

C++: Is it safe to pass an argument like unique_ptr::get() to function

getAName(getA().get())这样传递函数参数是否安全? getA() return 对象 unique_ptr<A>.

我在 VS 2010 上用下面的整个代码进行了测试,它有效。但我想确定它是否是 c++ 标准,与其他 c++ 编译器一起使用是否安全?

#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;
}

控制台中的输出是:

A()
A
~()

为了所有编译器的安全,是否有必要编写如下代码?

unique_ptr<A> a = getA();
getAName(a.get());

很安全。 getA() returns a temporary std::unique_ptr,完整表达式后会被销毁,其中包含对getAName()的调用。所以在 getAName() 的正文中,传递的指针仍然有效。

All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created, ...

注意,如果传入的指针存储在某个地方(例如全局变量),然后在以后使用(即在调用getAName()之后),则指针指向的对象已被临时对象销毁std::unique_ptr 并且指针悬空;那么对它的尊重将是 UB。如果是这种情况,如您所示,您可能需要一个命名变量。