在使用auto_ptr的时候很容易就会发生拥有权的转移,那么怎么才能防止这种情况发生呢?
常数型auto_ptr终止了“不经意转移拥有权”所带来的危险。
只要一个对象通过auto_ptr传递,就可以使用常数型auto_ptr来终结拥有权转移链,此后拥有权将不能再进行转移。
下面看代码示例:
//const auto_ptr 特性
#include<iostream>
#include<memory>
using namespace std;
template<class T>
ostream& operator<<(ostream&strm,const auto_ptr<T>&p)
{
if(p.get()==NULL)
{
cout<<"NULL";
}
else
{
cout<<*p;
}
return strm;
}
int main()
{
const auto_ptr<int> p(new int(42));//在这里,关键字const并非意味你不能更改auto_ptr所拥有的对象,而是意味你不能更改auto_ptr的拥有权。
const auto_ptr<int> q(new int(0));//相当于 int * const p; 即p的指向不能改变,但是p的值可以改变。
const auto_ptr<int> r;
cout<<"after initalization:"<<endl;
cout<<"p:"<<p<<endl;
cout<<"q:"<<q<<endl;
cout<<"r:"<<r<<endl;
*q=*p;//可以改变 *q的值,并把*p的值赋给*q
//*r=*p;//未定义的行为
*p=-77;
cout<<"after assigning values:"<<endl;
cout<<"p:"<<p<<endl;
cout<<"q:"<<q<<endl;
cout<<"r:"<<r<<endl;
//p=q;//不能改变拥有权
//r=p;
system("pause");
return 0;
}
运行结果:
通过运行结果可以看到,实际上,只是p所指的对象值发生了改变,而p对该对象的拥有权不能改变。除此之外,如果使用const auto_ptr作为参数,对新对象的任何赋值操作都会导致编译错误。