取消引用临时 unique_ptr
Dereferencing a temporary unique_ptr
unique_ptr<A> myFun()
{
unique_ptr<A> pa(new A());
return pa;
}
const A& rA = *myFun();
此代码可以编译,但 rA
包含垃圾。有人可以向我解释为什么此代码无效吗?
注意:如果我在取消引用之前将 myFun
的 return 分配给命名的 unique_ptr
变量,它工作正常。
unique_ptr
会将所有权传递给另一个 unique_ptr
,但在您的代码中没有任何内容可以从返回指针捕获所有权。换句话说,它不能转移所有权,所以它会被销毁。
正确的方法是:
unique_ptr<A> rA = myFun(); // Pass the ownership
或
const A rA = *myFun(); // Store the values before destruction
在您的代码中,返回的指针将被破坏,并且引用指向即将破坏的对象,之后使用该引用会调用未定义的行为。
unique_ptr<A> myFun()
{
unique_ptr<A> pa(new A());
return pa;
}
const A& rA = *myFun();
你在最后一行做了什么:
unique_ptr<A>* temporary = new unique_ptr<A>(nullptr);
myFun(&temporary);
const A& rA = *temporary.get();
delete temporary; // and free *temporary
当你删除temporary
时,它与你有一个契约,它拥有指向的指针和内存。所以它会破坏 A
并释放内存。
与此同时,您偷偷保留了一个指向该内存的指针作为对该地址处对象的引用。
您可以将指针转移到本地 unique_ptr:
unique_ptr<A> a = myFun();
或者您可以复制对象:
A = *myFun().get();
myFun()
s 临时对象的 'A' 仅在语句结束时销毁,因此它存在于副本中。
unique_ptr<A> myFun()
{
unique_ptr<A> pa(new A());
return pa;
}
const A& rA = *myFun();
此代码可以编译,但 rA
包含垃圾。有人可以向我解释为什么此代码无效吗?
注意:如果我在取消引用之前将 myFun
的 return 分配给命名的 unique_ptr
变量,它工作正常。
unique_ptr
会将所有权传递给另一个 unique_ptr
,但在您的代码中没有任何内容可以从返回指针捕获所有权。换句话说,它不能转移所有权,所以它会被销毁。
正确的方法是:
unique_ptr<A> rA = myFun(); // Pass the ownership
或
const A rA = *myFun(); // Store the values before destruction
在您的代码中,返回的指针将被破坏,并且引用指向即将破坏的对象,之后使用该引用会调用未定义的行为。
unique_ptr<A> myFun()
{
unique_ptr<A> pa(new A());
return pa;
}
const A& rA = *myFun();
你在最后一行做了什么:
unique_ptr<A>* temporary = new unique_ptr<A>(nullptr);
myFun(&temporary);
const A& rA = *temporary.get();
delete temporary; // and free *temporary
当你删除temporary
时,它与你有一个契约,它拥有指向的指针和内存。所以它会破坏 A
并释放内存。
与此同时,您偷偷保留了一个指向该内存的指针作为对该地址处对象的引用。
您可以将指针转移到本地 unique_ptr:
unique_ptr<A> a = myFun();
或者您可以复制对象:
A = *myFun().get();
myFun()
s 临时对象的 'A' 仅在语句结束时销毁,因此它存在于副本中。