Qt: does “new without delete” cause memory leaks with controls?

前端 未结 5 1800
[愿得一人]
[愿得一人] 2020-12-14 18:24

I was looking at Qt example here:

and inside the constructor, they have:

 Window::Window()
 {
     editor = new QTextEdit();   // Memory leak?
     Q         


        
5条回答
  •  没有蜡笔的小新
    2020-12-14 19:08

    As of C++14 you can use the std::make_unique() convenience function template for creating an std::unique_ptr<> that has exclusive ownership of the widget. Then, at the moment of passing the widget to addLayout(), you make the smart pointer give up ownership by calling release():

    auto buttonLayout = std::make_unique(); 
    // ...
    // an exception could be thrown here
    // ...
    layout->addLayout(buttonLayout.release());
    

提交回复
热议问题