简体   繁体   中英

using Qt objects with std::shared_ptr

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 :)

The arguments to std::make_shared are passed to the constructor of the class you're instantiating. So basically what you are doing is equivalent to:

new QVBoxLayout(new QVBoxLayout(centralwidget.get()))

I think what you are trying to do is :

centralwidget = std::make_shared<QWidget>(MainWindow);
verticalLayout = std::make_shared<QVBoxLayout>(centralwidget.get());

Have a look at the documentation of std::make_shared (for example here ). The whole point of this function is to allocate the reference count near the object instance in memory, so you have to let it do the allocation for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM