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的指针
}

猜你喜欢

转载自www.cnblogs.com/pylblog/p/9820771.html
今日推荐