#include <iostream> #include <tr1/memory> #include <boost/scoped_ptr.hpp> //scoped_ptr还不属于tr1 #include <boost/scoped_array.hpp> //scored_array也不属于tr1 #include <boost/shared_array.hpp> //shared_array也不属于tr1 class CTest { public: CTest() : m_id(0) {} CTest(int id) : m_id(id) {} ~CTest() { std::cout << "id :" << m_id << "-Destuctor isbeing called\n"; } void SetId(int id) { m_id = id; } int GetId() { return m_id; } void DoSomething() { std::cout << "id :" << m_id << "-DoSomething\n"; } private: int m_id; }; int main(int argc, char* argv[]) { // scoped_ptr boost::scoped_ptr<CTest> pTest(new CTest); pTest->SetId(123); pTest->DoSomething(); // error scoped_ptr(scoped_ptr const &) is private; // boost::scoped_ptr<CTest> pTest2(pTest); // error scoped_ptr & operator=(scoped_ptr const &) is private; // boost::scoped_ptr<CTest> pTest2; // pTest2 = pTest; // scoped_array boost::scoped_array<CTest> pVecTest(new CTest[2]); pVecTest[0].SetId(111); pVecTest[0].DoSomething(); // shared_ptr std::tr1::shared_ptr<CTest> pSt(new CTest); pSt->SetId(999); pSt->DoSomething(); std::tr1::shared_ptr<CTest> pSt2(pSt); // ok pSt2->DoSomething(); std::tr1::shared_ptr<CTest> pSt3; pSt3 = pSt2; // ok pSt3->DoSomething(); // weak_ptr std::tr1::weak_ptr<CTest> pWt(pSt); std::tr1::shared_ptr<CTest> pWtlock = pWt.lock(); // pWt->SetId(12345); // error weak_ptr can‘t used directly // pWt->DoSomething(); // error if (pWtlock == pSt) { std::cout << "pWt up to shared_ptr ok!\n"; pWtlock->SetId(12345); pWtlock->DoSomething(); } // shared_array boost::shared_array<CTest> pVecSt(new CTest[2]); pVecSt[0].SetId(888); pVecSt[0].DoSomething(); // auto_ptr std::auto_ptr<CTest> pAt(new CTest); pAt->SetId(789); pAt->DoSomething(); std::auto_ptr<CTest> pAt2(pAt); pAt2->DoSomething(); std::auto_ptr<CTest> pAt3; pAt3 = pAt2; pAt3->DoSomething(); std::cout << "pAt = " << pAt.get() << std::endl; // !!! std::cout << "pAt2 = " << pAt2.get() << std::endl; return 0; }
运行结果:
$ ./a.out id :123-DoSomething id :111-DoSomething id :999-DoSomething id :999-DoSomething id :999-DoSomething pWt up to shared_ptr ok! id :12345-DoSomething id :888-DoSomething id :789-DoSomething id :789-DoSomething id :789-DoSomething pAt = 0 pAt2 = 0 id :789-Destuctor isbeing called id :0-Destuctor isbeing called id :888-Destuctor isbeing called id :12345-Destuctor isbeing called id :0-Destuctor isbeing called id :111-Destuctor isbeing called id :123-Destuctor isbeing called
总结:
auto_ptr作为早期C++标准库函数因其诡异的行为而被诟病(被复制后原指针为NULL)
shared_ptr和weak_ptr已经纳入了std::tr1标准库内,引用计数型智能指针行为正常,一般和weak_ptr配合使用
shared_array用于new[]的智能数组指针,scoped_ptr,scoped_array和shared类似但不容许复制行为,它们都定义在boost库内,不属于标准C++库,不建议在工作环境中使用
时间: 2024-12-25 02:46:31