- ある開発者の覚書 - ソフトウェア開発者が情報処理に関する雑多な話題をジャンルを問わずに書き留めています.未来の私、私と同類のgeekたちへ

2008-08-22

weak pointer を bind (続き

昨日,調べろよ!とツッコミが(自分から)入ったので軽く調べてみました.

// test_bindWeakPtr.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>

using namespace std;

class CMyClass{
public:
CMyClass(){}
~CMyClass(){
cout<<"destruct:"<<this<<endl;
}
};

void HogeFunc(boost::weak_ptr<CMyClass> weakPtr){
if(weakPtr.lock()){
cout<<"alive:"<<weakPtr.lock().get()<<endl;
}else{
cout<<"dead"<<endl;
}
}

int _tmain(int argc, _TCHAR* argv[])
{
{
boost::function0<void> func1;
{
boost::shared_ptr<CMyClass> ptr1(new CMyClass());
func1 = boost::bind(&HogeFunc, ptr1);
cout<<"end of ptr1:"<<ptr1.get()<<endl;
}
func1();
cout<<"end of func1"<<endl;
}
{
boost::function0<void> func2;
{
boost::shared_ptr<CMyClass> ptr2(new CMyClass());
boost::weak_ptr<CMyClass> wptr(ptr2);
func2 = boost::bind(&HogeFunc, wptr);
cout<<"end of ptr2:"<<ptr2.get()<<endl;
}
func2();
cout<<"end of func2"<<endl;
}


return 0;
}




これを実行するとどうなると思いますか?
こうなります.


end of ptr1:004AC038
alive:004AC038
end of func1
destruct:004AC038
end of ptr2:004AC038
destruct:004AC038
dead
end of func2


つまりfunc1が存在する限りptr1は開放されません.func1にshared_ptrとしてbindされているので.デバッガで追ってみると


func1();


の中へ中へ入っていくとweak_ptrのコンストラクタが呼ばれていて,ファンクタを呼び出す時点でweak_ptrが生成されていることがわかります.

0 件のコメント:

ブログ アーカイブ