1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| #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; }
|