I'm trying to update a small utility application to a more modern C++ fashion, but I'm having problems using some Qt objects with std::shared_ptr, especially those that receive some other QWidget as a constructor argument.
For example:
private:
std::shared_ptr<QWidget> centralwidget;
std::shared_ptr<QVBoxLayout> verticalLayout;
public:
void setupUi(QMainWindow *MainWindow) // this pointer is a .get() from a shared_ptr
{
centralwidget = std::make_shared<QWidget>(new QWidget(MainWindow)); // compiles fine
verticalLayout = std::make_shared<QVBoxLayout>(new QVBoxLayout(centralwidget.get())); // does not compile
}
The compile error is:
Error 1 error C2664: 'QVBoxLayout::QVBoxLayout(QWidget *)' : cannot convert parameter 1 from 'QVBoxLayout *' to 'QWidget *' e:\microsoft visual studio 11.0\vc\include\memory 855
I cant seem to understand this error, I'm not converting anything, I'm just trying to create a QVBoxLayout object and passing a QWidget as its parent (like i would do with raw pointers).
In general, I try to avoid using shared_ptr for Qt GUI objects, since Qt already provides its own memory management mechanism. Each QObject possibly has a parent, and when this parent dies he deletes all of its children. A shared_pointer is not required here and doesn't give you any added value: you could perfectly use a raw pointer without creating a memory leak.
Generally speaking, if the QObject's parent dies before the last shared_ptr instance is deleted, you'll quickly get into troubles since the object will be deleted a second time when the last shared_ptr will be destroyed. That's not the case here, but be careful :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With