C++标准库---const auto_ptr特性

在使用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作为参数,对新对象的任何赋值操作都会导致编译错误。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值