I am trying to use the boost::signals2 functionalities in my program. In my "Main Class" called "Solid" I have a member which I initialize inside the constructor body (so after the member initializer list) like this:
pointer_M = boost::make_shared<OtherClass>(/*parameters,...*/);
If the signal is triggered by some function I do not want to call a member of "OtherClass" (to which pointer_M points) but a member from "Solid", i.e. the class which initialized pointer_M just.
I tried the following:
boost::signals2::connection tria_signal = /*...*/.connect( boost::signals2::signal<void()>::slot_type(&Solid::call_this_function, pointer_M.get()).track(pointer_M) );
"call_this_function" is a member function of Solid. Unfortunately there are a bunch of error messages. "OtherClass" and "Solid" are not related by inheritance.
I would appreciated getting some advice how to fix my issue since I am very unexperienced with boost.
Best
The point is we can't tell without a clearer description. It sure sounds like a no-brainer: signals are specifically used to decouple callers and callees.
So let me just make up your "dummycode" for you. I'm going to sidestep the enormous type-overcomplication that you showed in that line:
The whole idea of slots is that they generalize callables using type erasure. Just provide your callable in any compatible form and let the library deduce the arcane implementation types.
Live On Coliru
Prints
Crystal Ball: Can We Guess The Problem?
Maybe we can guess the problem: it looked like you were putting effort into tracking the lifetime of the object pointed to by
pointer_M. That's not useful, since thatOtherClassowns the signal in the first place, meaning that all connections are disconnected anyways when theOtherClassdisappears.Correct Lifetime Management
What you likely want is for the connection to disconnect when the lifetime of the
Solidobject ends, not theOtherClass. In general, I'd suggest usingscoped_connectionhere:Live On Coliru
Prints
Simplify
In your case, the
OtherClassis already owned by theSolid(at least it is created). It seems likely that having the shared-pointer is not necessary here at all:Live On Coliru
Because the members are destructed in reverse order of declaration, this is completely safe.
Architecture Astronauting
If you know what you're doing, and the
pointer_Mactually needs to be shared, then likely you want to track that pointer. You should probably be considering makingSolidalsoenable_shared_from_this. If you want to be really "Enterprise Grade Engineerâ„¢" about it, you could perhaps do something fancy with the aliasing constructor: What is shared_ptr's aliasing constructor for?