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)
	{

	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章