1 |
|
---|
2 | #include <iostream>
|
---|
3 | #include "boost/shared_ptr.hpp"
|
---|
4 | #include "boost/weak_ptr.hpp"
|
---|
5 |
|
---|
6 | class A;
|
---|
7 | class B;
|
---|
8 | typedef boost::shared_ptr<A> AStrongPtr;
|
---|
9 | typedef boost::weak_ptr<A> AWeakPtr;
|
---|
10 | typedef boost::shared_ptr<B> BStrongPtr;
|
---|
11 | typedef boost::weak_ptr<B> BWeakPtr;
|
---|
12 |
|
---|
13 |
|
---|
14 | class A {
|
---|
15 | public:
|
---|
16 | A() { std::cout << "Ctor A<"<<this<<">" << std::endl;}
|
---|
17 | virtual ~A() { std::cout << "Dtor A<"<<this<<">" << std::endl;}
|
---|
18 |
|
---|
19 | A(const A& aA) : b(aA.b) {std::cout << "CCtor A<"<<this<<">" << std::endl;}
|
---|
20 | A& operator=(const A& aA) {
|
---|
21 | std::cout << "opr= A<"<<this<<">" << std::endl;
|
---|
22 | if(&aA != this){
|
---|
23 | b = aA.b;
|
---|
24 | }
|
---|
25 | return *this;
|
---|
26 | }
|
---|
27 |
|
---|
28 | void setB(const BStrongPtr& aB) {b = aB;}
|
---|
29 | // BWeakPtr& getB() {
|
---|
30 | // std::cout << "Use non-const getB" << std::endl;
|
---|
31 | // return b;
|
---|
32 | // }
|
---|
33 | const BWeakPtr& getB() const {
|
---|
34 | std::cout << "Use const getB" << std::endl;
|
---|
35 | return b;
|
---|
36 | }
|
---|
37 |
|
---|
38 | private:
|
---|
39 | BWeakPtr b;
|
---|
40 | };
|
---|
41 |
|
---|
42 | class B {
|
---|
43 | public:
|
---|
44 | B() { std::cout << "Ctor B<"<<this<<">" << std::endl;}
|
---|
45 | virtual ~B() { std::cout << "Dtor B<"<<this<<">" << std::endl;}
|
---|
46 |
|
---|
47 | B(const B& aB) : a(aB.a) {std::cout << "CCtor B<"<<this<<">" << std::endl;}
|
---|
48 | B& operator=(const B& aB) {
|
---|
49 | std::cout << "opr= B<"<<this<<">" << std::endl;
|
---|
50 | if(&aB != this){
|
---|
51 | a = aB.a;
|
---|
52 | }
|
---|
53 | return *this;
|
---|
54 | }
|
---|
55 |
|
---|
56 | void setA(const AStrongPtr& aA) {a = aA;}
|
---|
57 | AWeakPtr& getA() {
|
---|
58 | std::cout << "Use non-const getA" << std::endl;
|
---|
59 | return a;
|
---|
60 | }
|
---|
61 | const AWeakPtr& getA() const {
|
---|
62 | std::cout << "Use const getA" << std::endl;
|
---|
63 | return a;
|
---|
64 | }
|
---|
65 |
|
---|
66 | private:
|
---|
67 | AWeakPtr a;
|
---|
68 | };
|
---|
69 |
|
---|
70 |
|
---|
71 | int main() {
|
---|
72 |
|
---|
73 | std::cout << "Create A & B" << std::endl;
|
---|
74 | AStrongPtr aA(new A);
|
---|
75 | BStrongPtr aB(new B);
|
---|
76 |
|
---|
77 | std::cout << "Make the association A <-> B" << std::endl;
|
---|
78 | aA->setB(aB);
|
---|
79 | aB->setA(aA);
|
---|
80 |
|
---|
81 | if(BStrongPtr aB = aA->getB().lock()) {
|
---|
82 | std::cout << "Use a B given by A->getB().lock() " << std::endl;
|
---|
83 | }
|
---|
84 |
|
---|
85 |
|
---|
86 |
|
---|
87 | std::cout << "return" << std::endl;
|
---|
88 |
|
---|
89 | return 0;
|
---|
90 |
|
---|
91 | }
|
---|