-
//[C++ Boost] boost::enable_shared_from_this ex2
//
// 6128 jyj
//
#include <iostream>
//#include <memory>
#include "boost/enable_shared_from_this.hpp"
#include <boost/shared_ptr.hpp>
#include <cassert>
//자신의 클래스 내부에서 자신의 shared_ptr<T> 값을 생성해 반환 해 주는 단순한 도구.
//단 자신은 shared_ptr로 생성되었어야 한다.
//한두줄로 직접 구현하든, 한두줄로 상속받아서 쓰든 ...
namespace BoostEnable_shared_from_thisTest02
{
class C1 : public boost::enable_shared_from_this<C1>
{
public:
int mV1;
boost::shared_ptr<C1> mSp;
C1(int value) : mV1(value)
{
printf("constructor\n");
}
~C1()
{
printf("destructor\n");
}
void funSpHardcoding()
{
auto t2 = boost::shared_ptr<C1>(mSp);
t2->prt();
//must call destroy
}
void funEs()
{
auto t2 = shared_from_this();
t2->prt();
}
void funSpWarning()
{
auto t2 = boost::shared_ptr<C1>(this); //warning
t2->prt();
}
void prt()
{
printf("test fun2 : %d\n", mV1);
}
};
void Main()
{
std::cout << __FILE__ << std::endl;
{//warning: no destructor
boost::shared_ptr<C1> sp(new C1(1));
sp->mSp = sp;
sp->funSpHardcoding();
}
{//boost::enable_shared_from_this
boost::shared_ptr<C1> sp(new C1(1));
sp->funEs();
}
{//err
boost::shared_ptr<C1> sp(new C1(1));
sp->funSpWarning();
}
}
}