標籤:
//C++智能指標模板類複習
#include<iostream>
#include<memory>
using namespace std;
//智能指標用於確保程式不存在記憶體和資源泄漏且是異常安全的。
//C++98中提供了auto_ptr,C++11摒棄了auto_ptr,並提出了unique_ptr 、shared_ptr、weak_ptr
void show1()
{
int* p = new int(4);
cout << *p << endl;
}
void show2()
{
int* p = new int(5);
try
{
if(1)//這裡只做假設
{
throw "error";
}
}
catch(const char* er)
{
cout << er << endl;
return;
}
cout << 1 << endl;
delete p;
}
void show3()
{
auto_ptr<int> p(new int(5));
cout << *p << endl;
}
unique_ptr<int> get()
{
unique_ptr<int> p(new int(5));
return p;
}
int main()
{
/*
//智能指標的目的
show1();//show1很明顯造成了記憶體泄露,雖然指標p隨著show1的結束而銷毀,但是開闢的堆空間仍然存留
show2();//show2很明顯如果try中遇到了錯誤程式退出,那麼也會造成記憶體泄露
show3();//auto_ptr實際上是一個用int執行個體化的模板類,對於開闢空間的回收寫在了類的解構函式中,所以隨著p對象的銷毀,堆空間也跟隨銷毀
*/
/*
//auto_ptr之間的指標對象在進行互相賦值時,將會轉讓對開闢的空間地址的所有權,如果不轉讓所有權的話,會對同一個堆記憶體進行多次回收,造成錯誤
auto_ptr<int> temp1(new int(5));
cout << *temp1 << endl;
auto_ptr<int> temp2(temp1);//此時temp1將開闢的堆空間的首地址傳給temp2,並且temp1不再擁有
//cout << *temp1 << endl;//這裡將會發生錯誤,因為temp1已經為空白
*/
/*
//shared_ptr之間的對象在進行互相賦值時不會轉讓所有權,這是因為shared_ptr採用了計數機制,當有多個智能指標同時指向一個堆空間時,
//一個指標對象的銷毀不會回收堆空間,只有當計數為1時,此時只有一個指標指向堆空間,此時指標對象銷毀時才回收堆空間
shared_ptr<int> temp3(new int(5));
cout << *temp3 << endl;
shared_ptr<int> temp4(temp3);
cout << *temp3 << endl;//此時不會報錯
*/
/*
//unique_ptr 類似於auto_ptr,也建立了所有權的概念,但是不用的是unique_ptr不允許普通對象之間的賦值,否則將會在編譯時間報錯,但是有一種特殊情況,我們接下來介紹
unique_ptr<int> temp5(new int(5));
cout << *temp5 << endl;
//unique_ptr<int> temp6(temp5);//這裡將會報錯
unique_ptr<int> temp6 = get(); //這是唯一的一種特殊情況,因為get函數把p返回後立即銷毀原先的指標,所以不存在日後出錯的說法,所以允許這種賦值
cout << *temp6 << endl;
*/
/*
//weak_ptr結合 shared_ptr 使用的特例智能指標。 weak_ptr 提供對一個或多個 shared_ptr 執行個體擁有的對象的訪問,但不參與引用計數。
//如果你想要觀察某個對象但不需要其保持活動狀態,請使用該執行個體。 在某些情況下,需要斷開 shared_ptr 執行個體間的循環參考。
shared_ptr<int> temp7(new int(5));
weak_ptr<int> a(temp7); //use_count成員函數用來顯示目前的shared_ptr指標的計數
cout << a.use_count() << endl; //因為a是對象,use_count是a的成員函數,所以用.
shared_ptr<int> temp8(temp7);
cout << a.use_count() << endl;
*/
return 0;
}
C++智能指標模板類複習