C++-智能指针-unique_ptr

     智能指针的设计是为了缓解C++的剧痛-内存管理,用C++编程经常存在动态创建内存没及时释放从而造成内存泄漏的问题。因为JVM,JAVA不存在这个问题。

    STL 提供了四种智能指针:auto_ptr、unique_ptr、shared_ptr 和 weak_ptr。C+11 已用 unique_ptr 替代了 auto_ptr。
简单MARK一下使用方法:
 

void  unique_ptr_main()
{
//1.智能指针的创建  
	unique_ptr<int> u_i; 	         //1.定义空智能指针
	u_i.reset(new int(3)); 	         //  绑定 
	unique_ptr<int> u_i2(new int(4));//2.创建
	

	//2.所有权的变化 必须要用MOVE  
	int* p_i = u_i2.release();	              //释放所有权   u_i2的值给p_i  u_i2放空
	unique_ptr<string> u_s(new string("abc"));//创建一个新的智能指针
	unique_ptr<string> u_s2 = std::move(u_s); //所有权转移(通过移动语义),u_s所有权转移后,变成“空指针” 
	                                          //u_s2 值为u_s, u_s放空
	u_s2.reset(u_s.release());	              //所有权转移
	u_s2 = nullptr;                           //显式销毁所指对象,同时智能指针变为空指针。与u_s2.reset()等价

	//3.不可以直接赋值
	unique_ptr<string> u_ps(new string("u_ps1"));
	unique_ptr<string> u_ps2(u_ps);	              //编译出错,已禁止拷贝
	unique_ptr<string> u_ps3 = u_ps;	          //编译出错,已禁止拷贝
	unique_ptr<string> u_ps4 = std::move(u_ps);   //控制权限转移

	
	//4 智能指针数组
	unique_ptr<string> films[5] =
	{
	unique_ptr<string>(new string("Fowl Balls")),
	unique_ptr<string>(new string("Duck Walks")),
	unique_ptr<string>(new string("Chicken Runs")),
	unique_ptr<string>(new string("Turkey Errors")),
	unique_ptr<string>(new string("Goose Eggs"))
	};
	unique_ptr <string> pwin;
	//films[2] loses ownership. 将所有权从films[2]转让给pwin,此时films[2]不再引用该字符串从而变成空指针
	pwin = std::move(films[2]);
	                 
    //5. 判空
	if (u_ps.get() != nullptr)
	{

	}
}

 

posted @ 2020-03-26 19:10  jasmineTang  阅读(81)  评论(0)    收藏  举报