C++中主要用New和Delete来分配和释放内存,但是有时候我们常常忘记Delete而造成内存泄露。为了避免这个问题,C++引入了智能指针模板类来管理动态内存。C++中智能指针有四种:auto_ptr,unique_ptr、share_ptr、weak_ptr。
1、auto_ptr(C++98的方案,C++11已放弃)
- auto_ptr要求对它拥有的指针完全占用,两个auto_ptr不能同时拥有同一个普通指针
- 例如:
auto_ptr<string> p1(new string("hello"));
auto_ptr<sting> p2;
p2 = p1; //不会报错,但是p2会剥夺p1的拥有权
std::cout << *p1 << std::endl; //报错<