標準庫 智能指針( smart pointer ) 是啥玩意兒 一,為什麼有智能指針??? c++程式員需要自己善後自己動態開闢的記憶體,一旦忘了釋放,記憶體就泄露。 智能指針可以幫助程式員 "自動釋放" 自己開闢的記憶體。 二,從哪裡看出來智能了??? 上面的代碼把p交給智能指針auto_ptr管理後, ...
標準庫 智能指針( smart pointer ) 是啥玩意兒
一,為什麼有智能指針???
c++程式員需要自己善後自己動態開闢的記憶體,一旦忘了釋放,記憶體就泄露。
智能指針可以幫助程式員"自動釋放"自己開闢的記憶體。
二,從哪裡看出來智能了???
int *p = new int(11);
auto_ptr<int> pa(p);//auto_ptr已經不推薦使用
//delete p;
上面的代碼把p交給智能指針auto_ptr管理後,就不需要自己去delete p。auto_ptr會去釋放p,所以體現出了"智能"。
三,哪裡看起來像指針了???
int *p = new int(11);
my_auto_ptr<int> pa(p);
*pa = 111;
cout << *pa << endl;
cout << *p << endl;
上面的代碼對智能指針pa使用了,*運算符,並且通過pa改變了p的值,所以看起來像指針哦。
class Test{
public:
void fun(){
cout << "func()" << endl;
}
};
Test* pt = new Test;
auto_ptr<Test> pa1(pt);
pa1->fun();
上面的代碼對智能指針pa1使用了,->運算符,並且通過pa1調用了對象pt的fun()成員方法,所以看起來像指針哦。
四,智能指針到底是個啥玩意兒???
是個模板類。
五,智能指針的是怎麼實現智能和指針的?
- 在智能指針的模板類里重寫operator* 運算符
- 在智能指針的模板類里重寫operator->運算符
- 在智能指針的模板類的析構函數里,釋放它指向的記憶體空間
- 管理指針的所有權和轉移(下麵的例子沒有實現)
#include <iostream>
#include <memory>
using namespace std;
template<typename T>
class my_auto_ptr{
public:
my_auto_ptr(T* p = nullptr):own(p!=nullptr),ptr(p){}
~my_auto_ptr(){
if(own){
delete ptr;
}
}
T& operator*()const{
return *ptr;
}
T* operator->()const{
return ptr;
}
private:
bool own;
T* ptr;
};
class Test{
public:
void fun(){
cout << "func()" << endl;
}
};
int main(){
//test1 老版本的auto_ptr的使用,現在不推薦使用
/*
int *p = new int(10);
auto_ptr<int> pa(p);
cout << *pa << endl;
string* ps = new string("aaa");
auto_ptr<string> pas(ps);
cout << pas->size() << endl;
*/
//test2 自己實現auto_ptr
int *p = new int(11);
my_auto_ptr<int> pa(p);
//delete p;
*pa = 111;
cout << *pa << endl;
cout << *p << endl;
Test* pt = new Test;
my_auto_ptr<Test> pa1(pt);
pa1->fun();
return 0;
}