auto_ptr

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

形象的用图形表示如下:

image

auto_ptr的拷贝构造函数和赋值操作符实际上并不复制已存储的指针,而是传递它,使第一个auto_ptr对象为空。由于auto_ptr不支持拷贝语义,所以不能用于STL容器,它的另一个缺点就是不能调用delete[],而无法用于数组。

介于auto_ptr有上述的缺点,所以在C++11标准中被废弃了,取而代之的是unique_ptr, shared_ptr及weak_ptr。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值