20140806--智能指针

1.shared_ptr的作用如同指针,但会记录有多少个shared_ptr指向同一个对象。就是引用计数。只有当指向这个对象的最后一个指针被销毁,也就是引用计数变为0的时候,这个对象才会被删除。头文件#include

#include <iostream>
#include <string>
#include <vector>
#include <memory>
using namespace std;


class Test{
    public:
        Test() { cout << "Test" << endl; }
        ~Test() { cout  << "~Test" << endl; }
};

int main(int argc, const char *argv[])
{
    shared_ptr<Test> ptr(new Test);

    cout << ptr.use_count() << endl;  //1
    cout << ptr.unique() << endl;  //true 1
    
    shared_ptr<Test> ptr2(ptr);  //类似于fd的复制
    cout << ptr.use_count() << endl;  //2 
    cout << ptr.unique() << endl;  // false 0

    return 0;
}

posted on 2014-08-06 20:48  detectiveh  阅读(85)  评论(0编辑  收藏  举报

导航