传递像getAName(getA().get())
这样的函数参数是安全的? getA()
返回一个对象 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()
返回 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 .如果是这种情况,如您所示,您可能需要一个命名变量。
关于C++:将像 unique_ptr::get() 这样的参数传递给函数是否安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43905276/