C++ 智能指針代碼解析
前言
如果在程序中使用new從堆分配內(nèi)存,等到不再需要時(shí),應(yīng)使用delete將其釋放,C++引入了智能指針auto_ptr,以幫助自動(dòng)完成這個(gè)過程,但是aoto_ptr也有其局限性,因此從Boost庫中又引入了三種智能指針unique_ptr shared_ptr weak_ptr。
1,aoto_ptr
// ConsoleApplication1.cpp : 定義控制臺(tái)應(yīng)用程序的入口點(diǎn)。
//
#include "stdafx.h"
#include <memory>
#include <string>
#include <iostream>
#include <ostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
auto_ptr<string> ptr1(new string("this is ptr!"));
auto_ptr<string> ptr2;
ptr2 = ptr1;
cout << &ptr2<<endl;
cout << *ptr2 << endl;
return 0;
}
- output :
003AFBC0
this is ptr!
但是如果輸出的是ptr1,程序會(huì)如何呢?
#include "stdafx.h"
#include <memory>
#include <string>
#include <iostream>
#include <ostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
auto_ptr<string> ptr1(new string("this is ptr!"));
auto_ptr<string> ptr2;
ptr2 = ptr1;
cout << &ptr1 <<endl;
cout << *ptr1 << endl; #這一步程序會(huì)崩潰
return 0;
}
崩潰原因: 首先ptr2 = ptr1表示ptr1將訪問的權(quán)限給了ptr2,同時(shí)意味了ptr1已經(jīng)沒有訪問字符串的權(quán)限,因此會(huì)報(bào)錯(cuò)。
那如何解決這個(gè)問題呢?引入了unique_ptr
2,unique_ptr
#include "stdafx.h"
#include <memory>
#include <string>
#include <iostream>
#include <ostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
unique_ptr<string> ptr1(new string("this is unique_ptr"));
unique_ptr<string> ptr2;
ptr2 = ptr1; #這一步編譯器會(huì)報(bào)錯(cuò)
return 0;
}
unique_ptr 替代auto_ptr實(shí)現(xiàn)獨(dú)占式,可以理解成,同一時(shí)刻只能有一個(gè)unique_ptr指向給定對(duì)象,unique_ptr對(duì)象始終是關(guān)聯(lián)的原始指針的唯一所有者。無法復(fù)制unique_ptr對(duì)象,它只能移動(dòng)。(這樣可以保證,不會(huì)出現(xiàn)auto_ptr那樣運(yùn)行時(shí)會(huì)出現(xiàn)的隱藏內(nèi)存崩潰問題)
int _tmain(int argc, _TCHAR* argv[])
{
unique_ptr<string> ptr1(new string("this is unique_ptr"));
unique_ptr<string> ptr2;
cout << &ptr1 << endl;
unique_ptr<string> ptr3(new string("other unique_ptr"));
cout << &ptr3 << endl;
cout << *ptr3 << endl;
return 0;
}
- output:
00D9F8B4
00D9F89C
other unique_ptr
3,share_ptr
// ConsoleApplication1.cpp : 定義控制臺(tái)應(yīng)用程序的入口點(diǎn)。
//
#include "stdafx.h"
#include <memory>
#include <string>
#include <iostream>
#include <ostream>
using namespace std;
class base{
public:
base()
{
cout << "begin..." << endl;
};
~base()
{
cout << "end..." << endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
base *a = new base();
shared_ptr<base> ptr1(a);
//shared_ptr<base> ptr2(a); ## 如果加上這句程序會(huì)崩潰,雙重管理陷阱,a對(duì)象被刪除了兩次
return 0;
}
- output:
begin...
end...
- share_ptr的循環(huán)陷阱
#include "stdafx.h"
#include <memory>
#include <string>
#include <iostream>
#include <ostream>
using namespace std;
class CB;
class CA
{
public:
CA()
{
cout << "CA call ..."<< endl;
}
~CA()
{
cout << "~CA call..."<< endl;
}
void setPtr(shared_ptr<CB> &ptr)
{
m_ptr_b = ptr;
}
int getCount()
{
return m_ptr_b.use_count();
}
private:
shared_ptr<CB> m_ptr_b;
};
class CB
{
public:
CB()
{
cout << "CB call..." << endl;
}
~CB()
{
cout << "~CB call..." << endl;
}
void setPtr(shared_ptr<CA> ptr)
{
m_ptr_a = ptr;
}
int getCount()
{
return m_ptr_a.use_count();
}
private:
shared_ptr<CA> m_ptr_a;
};
int _tmain(int argc, _TCHAR* argv[])
{
shared_ptr<CA> ptr_a(new CA);
shared_ptr<CB> ptr_b(new CB);
cout << " CA count is : " << ptr_a->getCount()<<endl;
cout << "CB count is:" << ptr_b->getCount()<< endl;
ptr_a->setPtr(ptr_b);
ptr_b->setPtr(ptr_a);
cout << " CA count is : " << ptr_a->getCount() << endl;
cout << "CB count is:" << ptr_b->getCount() << endl;
return 0;
}
上面這段程序的思路用下面張圖可以清晰的表示
圖片和代碼主要參考的是這篇很棒的博文:智能指針(三):weak_ptr淺析


運(yùn)行結(jié)果后發(fā)現(xiàn)并沒有調(diào)用析構(gòu)函數(shù)釋放內(nèi)存,以后存在內(nèi)存泄漏的風(fēng)險(xiǎn)
那如何去解決這個(gè)問題呢?,可以通過引入weak_ptr來解決,但是weak_ptr需要與share_ptr配合使用
4, weak_ptr
通過在兩個(gè)類中的一個(gè)成員變量改為weak_ptr對(duì)象,因?yàn)閣eak_ptr不會(huì)增加引用計(jì)數(shù),使得引用形不成環(huán),最后就可以正常的釋放內(nèi)部的對(duì)象,不會(huì)造成內(nèi)存泄漏
class CB
{
public:
CB()
{
cout << "CB call..." << endl;
}
~CB()
{
cout << "~CB call..." << endl;
}
void setPtr(shared_ptr<CA> ptr)
{
m_ptr_a = ptr;
}
int getCount()
{
return m_ptr_a.use_count();
}
private:
///shared_ptr<CA> m_ptr_a;
weak_ptr<CA> m_ptr_a; ## 改為weak_ptr對(duì)象
};


總結(jié)
遇到這類新的概念或者方法時(shí),一定要不嫌麻煩的一行一行代碼的去敲,在敲的過程中去理解吸收,如果只看不實(shí)踐,很有可能理解不深刻,無法體會(huì)到其中的原理和機(jī)制,所以對(duì)待問題一定要沉下心來多實(shí)踐。
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
詳解C++?OpenCV實(shí)現(xiàn)圖像拼接的原理及方法
本文以實(shí)現(xiàn)圖像拼接為目標(biāo),把分割開的圖像進(jìn)行拼接還原,核心的內(nèi)容包括:OpenCV圖像拼接相關(guān)原理以及OpenCV圖像拼接案例的實(shí)現(xiàn),感興趣的可以了解一下2022-07-07
一文帶你快速了解C/C++標(biāo)準(zhǔn)庫中的ptrdiff_t
ptrdiff_t是C/C++標(biāo)準(zhǔn)庫中定義的一個(gè)與機(jī)器相關(guān)的數(shù)據(jù)類型,ptrdiff_t類型變量通常用來保存兩個(gè)指針減法操作的結(jié)果,下面這篇文章主要給大家介紹了關(guān)于C/C++標(biāo)準(zhǔn)庫中ptrdiff_t的相關(guān)資料,需要的朋友可以參考下2022-11-11
五個(gè)經(jīng)典鏈表OJ題帶你進(jìn)階C++鏈表篇
做題之前呢,小編想提醒下大家,要三思而后行,不要一上來就嘎嘎敲代碼,要先學(xué)會(huì)自己畫圖分析,把自己的思路捋清楚,不要到時(shí)候?qū)懘a五分鐘,調(diào)試兩小時(shí),記住,編程思路很重要2022-03-03
如何在C++中實(shí)現(xiàn)一個(gè)正確的時(shí)間循環(huán)器詳解
這篇文章主要給大家介紹了關(guān)于如何在C++中實(shí)現(xiàn)一個(gè)正確的時(shí)間循環(huán)器的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
C++中事件機(jī)制的簡潔實(shí)現(xiàn)及需要放棄的特性
事件模型是被廣泛使用的好東西,但是C++標(biāo)準(zhǔn)庫里沒有現(xiàn)成的,現(xiàn)在VC11可以用在XP下了,那么就痛快的拿起C++11提供的先進(jìn)設(shè)施組合出一個(gè)輕便的實(shí)現(xiàn)吧感興趣的朋友可以了解下,或許對(duì)你有所幫助2013-02-02
C++中結(jié)構(gòu)體的類型定義和初始化以及變量引用
這篇文章主要介紹了C++中結(jié)構(gòu)體的類型定義和初始化以及變量引用,是C++入門學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-09-09

