Ale*_*der 5 c++ boost shared-ptr
这是代码示例
class A{
int i;
public:
A(int i) : i(i) {}
void f() { prn(i); }
};
int main()
{
A* pi = new A(9);
A* pi2= new A(87);
boost::shared_ptr<A> spi(pi);
boost::shared_ptr<A> spi2(pi2);
spi=spi2;
spi->f();
spi2->f();
pi->f();
pi2->f();
}
Run Code Online (Sandbox Code Playgroud)
输出:
87
87
0
87
Run Code Online (Sandbox Code Playgroud)
问题是为什么输出中为0?
文档说明:效果:等效于shared_ptr(r).swap(*this).
但是如果shared_ptr对象刚刚交换,结果应该是9.如果第一个对象被删除,应该有Segmentation fault.
为什么0?
仔细注意正在交换的内容:
shared_ptr(r).swap(*this)
// ^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
这是一个由...构建的临时对象r.临时超出范围并立即死亡,这对已拥有的资源产生了影响.由于在您的代码spi中唯一的所有者*spi,该对象被删除,您的后续访问pi->f()只是未定义的行为.
pi已被删除.访问已删除对象的成员是未定义的行为; 您可能会得到0,其他一些值或分段错误.