在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