Pergunta

I'm trying to develop a Qt Application for mobile phones, so I decided not to use any standard library(as I fear some platform may not yet be supported). So, I had to reimplement the smart pointer wrapper(using the standard draft, of course) without any standard headers. In Qt, there are some Widgets, such as QMenu and QToolBar which when needed to be created -- It is created as such

QMenu *mainMenu = new QMenu;
QToolBar *toolBar = new QToolBar;
//To add a new menu bar or ToolBar, we do
mainMenu = menuBar()->addMenu("&File");
//add all the elements to the first menuBar
mainMenu->addAction(QAction { });
mainMenu = menuBar()->addMenu("&Edit"); //for second Menu
//same goes for QToolBar

The only way I implemented the unique_ptr "observers" is to use the get(), operator* and operator-> member functions to access the underlying members. What's obvious is that MenuBar()->addNew() returns a new pointer to another mainMenu. Now to my question(s), what happens to the old pointer(s) that ? What keeps track of them? How can smart pointers be used in replacement of these naked pointers or do I have to stick with the "good old ways" of using strictly the naked pointers?

NOTE: All files can be found here

Foi útil?

Solução

as I fear some platform may not yet be supported

That feels like incorrect guess. Every mobile platforms support it these days and Qt does depend on the standard library explicitly these days.

Even if it did not, you do not need to implement your own smart pointer as Qt has been providing these for ages:

Here you can find a thorough explanation about them by Thiago.

So, the bottom line is just this: do not implement them yourself because you are reinventing the wheel and it is likely that you will need to fix bugs that had been fixed awhile ago. The ready-made solution will probably also scale better than your implementation from scratch and maintained by others without you needing to spend time with it.

If you only wish to deal with the automated construction and decontruction of QObject subclasses, you could also use the Qt parent/child hierarchy. Here you can read more about that one:

Object Trees & Ownership

That means, you could write something like this for QWidgets (because they are also QObjets):

QMenu *mainMenu = new QMenu(this);
QToolBar *toolBar = new QToolBar(this);

where this is basically the parent, like mainwindow, or it could be the Qt application object if you have one top-level widget, for instance, and so on.

Outras dicas

The simplest method for managing memory with Qt is by leveraging their "object tree" structure. You can read more about it in this question: Memory management in Qt?. Basically, Qt keeps a tree of parent-child relationships between QObjects and when the parent is deleted, it deletes all child objects. So feel free to use good, old new QObject(parent) and let Qt handle the cleanup for you.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top