Boost :: shared_ptr break loop with weak_ptr

I am now in a situation like:

struct A { shared_ptr<B> b; }; struct B { shared_ptr<A> a; }; //... shared_ptr<A> a(new A()); shared_ptr<B> b(new B()); a->b(b); b->a(a); 

I know this will not work because the links will continue to point to each other. I was also told that weak_ptr solves this problem.

However, weak_ptr does not have an overload of get or -> . I heard mentions of "use lock() ", but can anyone give some code examples on how to do this correctly?

+2
source share
4 answers

Come on now.

http://boost.org/doc/libs/1_42_0/libs/smart_ptr/weak_ptr.htm

^^^^^ EXAMPLE CORRECTLY. ^^^^^^

Damn!

-one
source

I think the big problem here is ambiguous property. You would be better off deciding whether A encapsulate B or vice versa. If this is not possible, you are still better off introducing another class C that owns both A and B

Assuming A belongs to B , you can write:

 classs B; classs A { private: boost::scoped_ptr<B> b_; public: A() : b_(new B()) {} } class B { private: A* a_; public: B(A* a) : a_(a) {} } 

And so on. You can even get rid of scoped_ptr by making B a local variable or manually deleting it in the destructor.

The Google C ++ Style Guide has more to say about this in a section called Smart Pointers .

NTN

+6
source

Have you checked the boost link for weak_ptr ?

 shared_ptr<int> p(new int(5)); weak_ptr<int> q(p); // some time later if(shared_ptr<int> r = q.lock()) { // use *r } 

The idea is that you block weak_ptr , thereby getting shared_ptr , which has statements.

First check if the resulting pointer points to something. A weak_ptr does not determine the life of the resource, but allows you to check whether the resource has already been destroyed.

+2
source
 #include <boost/shared_ptr.hpp> #include <boost/weak_ptr.hpp> struct B; struct A { boost::weak_ptr< B > b; }; struct B { boost::weak_ptr< A > a; }; int main() { boost::shared_ptr<A> a(new A()); boost::shared_ptr<B> b(new B()); a->b = b; b->a = a; boost::shared_ptr<A> another_a( b->a.lock() ); } 

you can advertise weak_ptr to shared_ptr with weak_ptr::lock .

-one
source

All Articles