最近在看《Effective C++》这本书,上面看到了智能指针这一部分,看后很有感触,所以想把自己看到的写下来,加深一下印象
auto_ptr有一个不寻常的性质:若通过copy构造函数或者copy assignment操作复制它们,它们会变成null,而复制所得的指针将取得资源的唯一拥有权。
举个例子说明一下:
std::auto_ptr<A> pInv1(CreateInvestment());//pInv1指向CreateInvestment()返回物
std::auto_ptr<A> pInv2(pInv1);//现在pInv2指向对象,pInv为null
pInv2=pInv1;//现在pInv1指向对象,pInv2为空
A::A():_localint(0)
{
}
A::~A()
{
}
int _tmain(int argc, _TCHAR* argv[])
{
std::auto_ptr<A> ptr1(new A());
std::auto_ptr<A> ptr2(ptr1);
cout<<ptr2->_localint<<endl;
//cout<<ptr1->_localint<<endl;//执行到这的时候,程序会报错!
ptr1 = ptr2;
cout<<ptr1->_localint<<endl;//程序又正常了
return 0;
}
这样指针在释放的时候,对象会被释放一次以上。所以要注意!!!
而tr1::shared_ptr可以将多个指针同时指向同一个对象。
若使用tr1::shared_ptr
tr1::shared_ptr<A> ptr1(new A());
tr1::shared_ptr<A> ptr2(ptr1);
cout<<ptr2->_localint<<endl;
cout<<ptr1->_localint<<endl;
程序正常通过!