智能指针

#include <iostream>
using namespace std;
#include <memory>


//容器使用迭代器进行遍历使用

//shared_ptr 强引用,将指针所指之物与自己的声明周期紧密联系,一旦自己析构,就会使得引用计数减1
//weak_ptr 弱引用   不能决定底层指针的生命周期,只能根据自己的成员对象去探测是否对象存活

shared_ptr<string> test()
{
	
	shared_ptr<string> st(new string("zhongguo"));
	//shared_ptr<string>  tt = new string("hha");//error shared_ptr构造函数explicit
	string::iterator tt = (*st).begin();
	
	shared_ptr<string> zz = st;//使用赋值运算符成员函数,引用计数加1
	for (;tt!=(*st).end(); ++tt)
	{
		cout<<*tt;
	}

	weak_ptr<string> rt(zz); //用shared_ptr来初始化weak_ptr
	shared_ptr<string> ty = rt.lock();//使用lock进行提升到shared_ptr
	string::iterator at = (*ty).begin();
	for (;at!=(*ty).end(); ++at)
	{
		cout<<*at;
	}
	return ty;
}

int main()
{
	/*weak_ptr<string> re = test();//如果用其接收一个shared_ptr返回值,先进性复制,然后转换,然后释放,
			//则shared_ptr对象会被释放,weak_ptr接收到NULL
	shared_ptr<string>  ss = re.lock();*/
	shared_ptr<string>  ss = test();
  	cout<<endl;
	if (ss != NULL)
	{	//test返回类型位weak_ptr,或者返回类型为shared_ptr,但是用weak_ptr类型接收并且去提升为shared_ptr
		cout<<"error";
	}
	else//weak_ptr属于弱引用,不能决定指针的生命,只能使用时候去探测其是否存活
	{ //返回类型为shard_ptr,并用shared_ptr接收
		cout<<"right"<<endl;
	}
	return 0;
}


//int main()
//{
//	auto_ptr<string> st(new string("nihao"));
//	string::iterator t=(*st).begin();
//	
//	auto_ptr<string> tt;
//	tt = st; //auto_ptr一旦使用了赋值运算符就会发生原来的auto_ptr失去管理权,不能在去使用原来的智能指针
//
// //	for ( ;t != (*st).end(); ++t)//error
//	//{
//	//	cout<<*t;
//	//}
//	return 0;
//}
int main()
{
	int *ja =new int(3);
	shared_ptr<int> i(ja);
	shared_ptr<int> j;
	j = i;
	*j = 12;//不提供写时复制功能
	cout<<"*j is  "<<*j<<endl;
	cout<<"*i is  "<<*i<<endl;
	return 0;
}
int main()
{
	unique_ptr<string> st(new string("niaho"));
	string::iterator it=(*st).begin();
	for( ;  it!=(*st).end(); ++it)
	{
		cout<<*it;
	}
	//unique_ptr<string> tt(st);//复制构造函数不允许
	//tt = st; //赋值运算符重载函数不允许
	return ;
}
智能指针的循环引用使得内存泄漏
class CCycleRef  
{  
public:  
    ~CCycleRef()  
    {  
        cout <<"destroying CCycleRef"<<endl;  
    }  
  
public:  
    shared_ptr<CCycleRef> selfRef; 
	//weak_ptr<CCycleRef> selfRef;  
};  
  
void CycleRefTest()  
{  
    shared_ptr<CCycleRef> cyclRef(new CCycleRef());  
    cyclRef->selfRef = cyclRef;  
    cout<<"reference count:"<<cyclRef.use_count()<<endl;  
}  
int main()  
{  
    CycleRefTest();  
    return 0;  
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值