Qt QObject and boost::enable_shared_from_this

924 views Asked by At

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.

2

There are 2 answers

1
Angew is no longer proud of SO On BEST ANSWER

You mentioned in the comments that you don't create a shared_ptr before you call shared_from_this(). But that's the problem. x.shared_from_this() only works once a shared_ptr to x exists. If you never create one, you're violating a precondition of shared_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.

1
ChrisPeterson On

Ok folks, it has been my fault but the answer could help to someone:

  1. As Angew said it is necessary to create the first instance of MainWindow using a shared_ptr (I didn't understand your question the first time).
  2. I was doing this but I was using the std::shared_ptr implementation instead of the boost::shared_ptr one. Mixing both was producing this results.
  3. It works now but as Angew said one has to be very careful using shared_ptr's with the Qt ownership scheme.
  4. The inheritance order specified in the MainWindow declaration is the only one valid. As Angew said: "When inheriting from QObject or a class derived from it, QObject (or that derived class) must be the first one in the base class list. So that won't work"

Thank you