boost学习之--shared_ptr

    在boost中,有一个智能指针类shared_ptr能够管理好咱们的指针。这里我不详解,如下列出使用例子。本身现写现调经过的哈:
ios

#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>

using namespace std;
using namespace boost;

class Person
{
public:
    Person(string name, int age) : m_name(name), m_age(age) { cout << "construct" << endl; }
    ~Person() { cout << "destruct" << endl; }

    void print(void) { cout << "name:" << m_name << ", age:" << m_age << endl; }
private:
    string m_name;
    int m_age;
};

int main( int argc, char *argv[] )
{
    cout << "Hello, This is a test of shared_prt" << endl;
    if (1) {
        shared_ptr<Person> pMan = make_shared<Person>("Peter Lee", 24);
        pMan->print();
    }
    cout << "End test" << endl;
    return 0;
}
    编译运行结果:

    其实上面展现的功能scoped_ptr也有。但scoped_ptr是不可复制的,而shared_ptr的特色是任意复制的。shared_ptr内部有一个引用计数器,记录当前这个指针被几个shared_ptr共享。 spa

相关文章
相关标签/搜索