0%

boost enable shared from this

Code Example

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;

/*
enable_shared_from_this has become part of C++ 11 standard.

https://blog.csdn.net/csfreebird/article/details/8282518
https://stackoverflow.com/questions/712279/what-is-the-usefulness-of-enable-shared-from-this
*/

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()
{// lead to multiple release on same resouce
return boost::shared_ptr<Y>(this); // don't do 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)); // p and q must share ownership

/*
Y::Y()
Y::~Y()
*/
}

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)); // p and q must share ownership

/*
Y::Y()
Y::~Y()
Y::~Y()
*/
}

int main()
{
//test_safe();
test_dangerous();
return 0;
}

Reference

History

  • 20180523: created.