使用boost的智能指针需要包含头文件"boost/smart_ptr.hpp",c++11中需要包含头文件<memory>

1、auto_ptr、scoped_ptr、scoped_array

  ①、auto_ptr是C++标准中的智能指针,在指针退出作用域的时候自动释放指针指向的内存,即使是异常退出的时候。auto_ptr实际上是一个对象,重载了operator*和operator->,且提供了一些成员函数,比如使用成员get()可以获得对应类型的原始指针。

  auto_pt的特点是可以对其进行复制和赋值,但同一时刻只能有一个auto_ptr管理指针。

  使用之前需要包含头文件<memory>,eg:

boost-智能指针
#include <memory>
#include <cassert>
int main()
{
    std::auto_ptr<int> ap1(new int(5));
    cout << *ap1 << endl;

    int* p = ap1.get();
    cout << *p << endl;

    std::auto_ptr<int> ap2(ap1);//ap1失去管理权,不再拥有指针,ap2得到管理权
    assert(ap1.get() == 0);//get()获得的指针为空

    return 0;
}
View Code

相关文章: