I want to use boost signals2 with automatic connection management in a multithreaded application. My class inherits from enable_shared_from_this<>
and i want to connect a member method from within another member method. The connection might be rebuilt frequently so my code should be as fast as possible (despite from the boost signals2 performance itself):
typedef boost::signals2::signal<void ()> signal_type;
struct Cat : public enable_shared_from_this<Cat>
{
void meow ();
void connect (signal_type& s)
{
// can't write this
s.connect (signal_type::slot_type (&Cat::meow, this, _1).track (weak_from_this ()));
// ok, but slow?! two temporary smart pointers
weak_ptr<Cat> const myself (shared_from_this ());
s.connect (signal_type::slot_type (&Cat::meow, this, _1).track (myself));
}
// i am missing something like this in the base class
// protected:
// weak_ptr<Cat> const& weak_from_this ();
};
I know that my design goals might be conflicting (automatic connection management and thread safety but also fast code) but anyway:
Why does
enable_shared_from_this<>
lack direct access to the embeddedweak_ptr<>
? I can't see an opposing reason. Is there no use case similar to mine?Is there a faster workaround than the one above?
Edit:
I know i can do somethink like this, but i want to avoid the additional storage/init-check penalty:
template <typename T>
struct enable_weak_from_this : public enable_shared_from_this<T>
{
protected:
weak_ptr<T> /* const& */ weak_from_this ()
{
if (mWeakFromThis.expired ())
{
mWeakFromThis = this->shared_from_this ();
}
return mWeakFromThis;
}
private:
weak_ptr<T> mWeakFromThis;
};