Code Example
#include <iostream>
#include <string>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
using namespace std;
using namespace boost;
class Y : public boost::enable_shared_from_this<Y>
{
public:
Y()
{
cout << "Y::Y()" << endl;
}
~Y()
{
cout << "Y::~Y()" << endl;
}
boost::shared_ptr<Y> f()
{
return shared_from_this();
}
boost::shared_ptr<Y> f_dangerous()
{
return boost::shared_ptr<Y>(this);
}
};
void test_safe()
{
boost::shared_ptr<Y> p(new Y);
boost::shared_ptr<Y> q = p->f();
assert(p == q);
assert(!(p < q || q < p));
}
void test_dangerous()
{
boost::shared_ptr<Y> p(new Y);
boost::shared_ptr<Y> q = p->f_dangerous();
assert(p == q);
assert(!(p < q || q < p));
}
int main()
{
test_dangerous();
return 0;
}
Reference
History