天天看點

boost shared_ptr 用法

1 shared_ptr    不明确的符号

boost的一些庫,比如share_ptr已經被高版本的stl采納了.如果在代碼中沒有指定命名空間,編譯器就無法得知應該使用哪個命名空間之下的代碼進行編譯如下引入的命名空間的方式不推薦

using namespace std;

using namespace tr1;

using namespace boost;

實際上兩個智能指針是一樣的,你隻需要用一個即可.如果你一定要兩個都用,那麼不要寫上面的語句.而是應該寫std::tr1::xxxx, boost:xxxx

2 shared_ptr 作為類成員函數的寫法

#include <iostream>

#include <boost/shared_ptr.hpp>

struct SStudentInfo

{

public:

SStudentInfo() 

std::cout << "Create instance" << std::endl;

};

~SStudentInfo() 

std::cout << "Free instance" << std::endl;

}

class CTestSharedPtr

CTestSharedPtr() 

//m_student = new SStudentInfo();//error

m_student = boost::shared_ptr<SStudentInfo>(new SStudentInfo());

~CTestSharedPtr() {};

private:

boost::shared_ptr<SStudentInfo> m_student;

    本文轉自fengyuzaitu 51CTO部落格,原文連結:http://blog.51cto.com/fengyuzaitu/1945834,如需轉載請自行聯系原作者

繼續閱讀