I’m try to use tr1‘s shared_ptr and Qt 4.8.2 but I have some troubles.
Here my code :
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <string>
#include <tr1/memory>
using namespace std::tr1;
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QTreeView>
#include <QListView>
#include <QWidget>
#include <iostream>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
shared_ptr<QHBoxLayout> mainLayout(new QHBoxLayout);
shared_ptr<QTreeView> mainFeeds(new QTreeView);
mainLayout->addWidget(mainFeeds.get());
shared_ptr<QWidget> mainWidget (new QWidget);
mainWidget->setLayout(mainLayout.get()); // <--- this line
shared_ptr<QWidget> rightWidget(new QWidget);
shared_ptr<QVBoxLayout> rightLayout(new QVBoxLayout);
shared_ptr<QListView> rightItems(new QListView);
rightLayout->addWidget(rightItems.get());
shared_ptr<QListView> rightPreview(new QListView);
rightLayout->addWidget(rightPreview.get());
rightWidget->setLayout(rightLayout.get());
mainLayout->addWidget(rightWidget.get());
this->setCentralWidget(mainWidget.get());
}
MainWindow::~MainWindow()
{
delete ui;
}
And the output (I use Qt Creator) :
Starting /path/myproject-build-desktop-Qt_4_8_2_in_PATH_local_Release/myproject…
The program has unexpectedly finished.
/path/myproject-build-desktop-Qt_4_8_2_in_PATH_local_Release/myproject exited with code 0
When I comment the marked line, the program runs but I have an empty window.
I have two questions :
- Why this line makes an error?
- Is it the right way to use smart pointers (in fact to build robust C++ code) with Qt?
For your help,
In advance,
Thanks.
Qt manages objects lifetime in its own manner. When you make
Achild ofB, thenAwill bedelete‘d whenBdestroyed.So, in this line
you make
mainLayoutchild ofmainWidget.As
mainWidgetdeclared aftermainLayout, it will be removed first. AndmainLayoutwill be removed also. But thenshared_ptrwill try to removemainLayoutagain.In
Qtyou should be very carefull using smart pointers. Qt memeory management often take ownership of object, (but not always). Also you may prefer using nativeQtsmart pointersQPointeras a week pointer toQObjectQScopedPointeras replacement ofstd::unique_ptretc.QSharedPointer/QExplicitlySharedPointerfor shred pointers.