I am creating a mixin between two classes using the boost::enable_shared_from_this template. So I am adding a new functionality to this class:
class MyOldClass :
public Connection,
public boost::enable_shared_from_this<MyOldClass>
{ ... };
I did use this before with a normal class (not a QtObject, just a C++ plain class) and everything works.
But now I am doing the same with a QMainWindow and it basically crash:
class MainWindow :
public QMainWindow,
public Connection,
public boost::enable_shared_from_this<MainWindow>
{ Q_OBJECT ... };
Is it possible that there is any problem doing this with a QObject? Not sure why this is happening.
Thank you.
You mentioned in the comments that you don't create a
shared_ptr
before you callshared_from_this()
. But that's the problem.x.shared_from_this()
only works once ashared_ptr
tox
exists. If you never create one, you're violating a precondition ofshared_from_this()
, so your program has undefined behaviour.shared_from_this()
only serves to retrieve a pointer sharing ownership with existing shared pointers; it cannot be used to create the first one.