auto_ptr
在C++ 98中,智能指针通过一个模板类型auto_ptr来实现,程序员只需将new操作返回的指针作为auto_ptr的初始值即可,不用再显式的调用delete。比如:
auto_ptr(new int);
- 1
这在一定程度上避免了堆内存忘记释放而造成的内存泄漏。但是auto_ptr存在很明显的缺点,它采取了独占所有权模式,这样两个相同类型的指针不能同时指向相同的资源。比如下面的代码:
// C++ program to illustrate the use of auto_ptr
#include<iostream>
#include<memory>
using namespace std;
class A
{
public:
void show() { cout << "A::show()" << endl; }
};
int main()
{
// p1 is an auto_ptr of type A
auto_ptr<A> p1(new A);
p1 -> show();
// returns the memory address of p1
cout << p1.get() << endl;
// copy constructor called, this makes p1 empty.
auto_ptr <A> p2(p1);
p2 -> show();
// p1 is empty now
cout << p1.get() << endl;
// p1 gets copied in p2
cout<< p2.get() << endl;
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
输出为:
A::show()
0x1b42c20
A::show()
0
0x1b42c20
- 1
- 2
- 3
- 4
- 5
形象的用图形表示如下:
auto_ptr的拷贝构造函数和赋值操作符实际上并不复制已存储的指针,而是传递它,使第一个auto_ptr对象为空。由于auto_ptr不支持拷贝语义,所以不能用于STL容器,它的另一个缺点就是不能调用delete[],而无法用于数组。
介于auto_ptr有上述的缺点,所以在C++11标准中被废弃了,取而代之的是unique_ptr, shared_ptr及weak_ptr。