在boost中,有一个智能指针类shared_ptr可以管理好我们的指针。这里我不详解,以下列出使用例子。自己现写现调通过的哈:
#include编译运行结果:#include #include 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 pMan = make_shared ("Peter Lee", 24); pMan->print(); } cout << "End test" << endl; return 0;}
![](http://static.oschina.net/uploads/space/2013/0319/233234_oIFO_243525.png)
其实上面展示的功能scoped_ptr也有。但scoped_ptr是不可复制的,而shared_ptr的特点是任意复制的。shared_ptr内部有一个引用计数器,记录当前这个指针被几个shared_ptr共享。