1

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 ?

Teivaz
  • 5,462
  • 4
  • 37
  • 75
Ben D
  • 465
  • 1
  • 6
  • 20
  • 2
    Can you show us some code? –  Aug 01 '17 at 14:42
  • Yes, this is not any use without sufficient code for people to understand what is going on internally. – underscore_d Aug 01 '17 at 14:53
  • I think what you want is a [`std::weak_pointer`](http://en.cppreference.com/w/cpp/memory/weak_ptr) for the signal handler, but I agree that having code would make this easier to understand. – Daniel H Aug 01 '17 at 15:20
  • Here is a part of the code that can be usefull:https://gist.github.com/bend/c923187223e0ade3117168bee874feea – Ben D Aug 02 '17 at 07:20
  • The weird thing is that I don't see any call of the destructor (I've put a cout in the desctructor) but I don't see any leak of the object in valgrind... – Ben D Aug 02 '17 at 11:57

1 Answers1

2

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.

Ben D
  • 465
  • 1
  • 6
  • 20