Awesome Hacks!

プログラミング初心者なので地道に勉強していきます。分からない人の立場から整理していきます。

C++_boost::shared_ptrの使い方(使用例)と、生ポインタの取得、NULLチェック

※本稿はshared_ptrの基本的な使い方を解説したものではありません。あくまでも、私が業務上にて必要となった知識を要約したものです。基本的な使い方については、他のサイトをご覧ください。(そのうちいつか基本的な使い方について整理できればいいなとは考えていますが・・・)


 
【使用例】

#include <iostream>
#include <boost/shared_ptr.hpp>
using namespace std;

typedef boost::shared_ptr<int> sharedInt_ptr;

class Human {
	private:
		sharedInt_ptr num;
	public:
		Human() : num() {} // numをNULLで初期化
		sharedInt_ptr get_num(){
			return num;
		}
};

int main(){
	// 下記はコンパイルエラー
	// boost::shared_ptr<Human> ptr;		オブジェクトが無いから参照できない?!
	// ptr = new Human();

	// 格納したいポインタをshared_ptrのコンストラクタの引数に渡す必要がある様子

	// 下記のように静的資源の場合、shared_ptr使用可
	// boost::shared_ptr<Human> ptr(new Human);
	boost::shared_ptr<Human> ptr(new Human());

	cout << "<< 事前確認 >>" << endl;
	// NULLはC言語との互換性のために残されたマクロ定義で、
	// C++では0を使用するため「0」であればNULL
	cout << "      ptr->get_num() : " << ptr->get_num() << "\n" << endl;

	cout << "<< shared_ptr型のNULL確認 >>" << endl;
	cout << "    ** sharedInt_ptr型(shared_ptr<int>型)のポインタno(ptr->get_num())のNULLチェック" << endl;
	// コンストラクタで初期化したsharedInt_ptr型のnumを普通に関数で取得してNULL確認
	// 注意 : ptrはshared_ptr<Human>型のポインタ、ptr->get_num()はshared_ptr<int>型(sharedInt_ptr型)の値を返す
	sharedInt_ptr no = ptr->get_num();
	if (no == NULL) {
		cout << "      no == NULL\n" << endl;
	} else {
		cout << "      no != NULL\n" << endl;
	}

	cout << "<< shared_ptr型の「生ポインタ」のNULL確認 >>" << endl;
	cout << "    ** sharedInt_ptr型(boost::shared_ptr<int>型)のポインタno(ptr->get_num())の「生ポインタ(通常のポインタ)」のNULLチェック" << endl;

	// boost::shared_ptr<T>型の場合「T*」型のポインタが返ってくる
	// 今回は、boost::shared_ptr<int>型なので「int*」型のポインタが返ってくる
	if (no.get() == NULL) {		// 生ポインタがNULLかチェック
		cout << "      no.get() == NULL\n" << endl;
	} else if(no.get() == reinterpret_cast<int*>(NULL)) {
		cout << "      no.get() == reinterpret_cast<int*>(NULL)\n" << endl;
	} else {
		cout << "      no.get() != NULL && no.get() != reinterpret_cast<int*>(NULL)\n" << endl;
	}

	// 結論 : shared_ptr<T>型の生ポインタは「T*」型
	return 0;
}


【実行結果】

$ sharePtr
<< 事前確認 >>
      ptr->get_num() : 0x0

<< shared_ptr型のNULL確認 >>
    ** sharedInt_ptr型(shared_ptr<int>型)のポインタno(ptr->get_num())のNULLチェック
      no == NULL

<< shared_ptr型の「生ポインタ」のNULL確認 >>
    ** sharedInt_ptr型(boost::shared_ptr<int>型)のポインタno(ptr->get_num())の「生ポインタ(通常のポインタ)」のNULLチェック
      no.get() == NULL

$