简体   繁体   中英

C++ shared_ptr std::bind and std::function

I have the following:

class B listens to a boost::signal2 of class C and when triggered will execute a callback given by class A and that executes a method in class A

A , B and C , D are all std::shared_ptr .

The problem is that when class D releases the pointer to class B , B is not being deleted because of the signal handler. Even if I call disconnect on the boost::connection I have the same problem.

Any Idea how I can fix that ?

So the problem was due to a shared_ptr cycle.

Class A was passing to class B an std::function that holds a shared_ptr to class A , so class A was never being deleted.

eg. B.route(std::bind(&A::myFunc, shared_from_this()));

I fixed it with a lambda function and a weak_ptr in class A :

std::weak_ptr<A> wp = shared_from_this();
  A.route(std::bind([wp]() {
   auto p = wp.lock();
   if(wp)
     wp->myFunc();
}));

That way my function myFunc is only called if A is still valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM