/*
auto_ptr的實現
*/
#include<bits/stdc++.h>
using namespace std;
namespace P{
template <typename T>
class Auto_ptr{
public:
Auto_ptr(T *da){
s=da;
}
Auto_ptr(Auto_ptr &da){
s=da.s;
da.s=NULL;
}
~Auto_ptr(){
if(s!=NULL){
cout<<"調用析構"<<endl;
delete(s);
}
}
T& operator*(){
return *s;
}
T* operator->(){
return s;
}
protected:
T *s;
//還可以在這裏加一個標記,判斷屬不屬於自己,結果一致。
};
}
//auto_ptr缺點很明顯,管理權交給別人之後,自己指向爲空。
struct node{
int p;
};
int main(){
using namespace P;
int *da=new int(10);
Auto_ptr<node> a(new node{1});
Auto_ptr<node> b(a);
return 0;
}
auto_ptr簡單實現
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.