1. 程式人生 > >C++學習筆記5_智慧指標

C++學習筆記5_智慧指標

1. 一般的指標
int main(void)
{
int *p=new int;
*p=20;
delete p;
return 0;
}
智慧指標能自動回收
#include<memory> 記得要引用標頭檔案
int main(void)
{
//auto_ptr<int>模板寫法
auto_ptr<int> ptr(new int);
}
auto_ptr<>其實是一個模板類;
使用智慧指標,就不用自己delete了,也能自行呼叫解構函式
2.
class A
{
public :
A(int a)
{
//...
}
func()
{
//...
}
}
int main(void)
{
auto_ptr<A> ptr(new A(10));
ptr->func();
(*ptr).func();
//auto_ptr肯定過載了->和*操作符,並且在析構時,delelte了A的指標
}