How are destructors called when instantiated in main.cpp
-
This is a fundamental question, but I can't figure out how classes instantiated in main.cpp are deleted.
I have the following code in my main.cpp:
@#include "mainwindow.h"
#include <QApplication>
#include <QString>
#include <QDebug>
#include <Underworld/Base/Underworld.h>
#include <Underworld/Base/underworldtools.h>int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QString loginName = uw::getLoginName();
QString userRootPath = QString("/Users/%1").arg(loginName);
QString corePath = QString("/Users/%1/Nile/core").arg(uw::getLoginName());
uw::world = new Underworld(userRootPath, corePath, true);MainWindow w; w.show(); return a.exec();
}@
As you can see, I have instantiated the class Underworld() in main.cpp. This is the "mothership" of a bunch of stuff that needs to go away when the application quits. I don't see any of my destructors being called when I quit the application. Wonder what/if I'm missing something.
Thanks in advance.
-
Sorry but in your class (Underworld) do you implement the destroyer method ?
I think yes.
Then, when the program finish put the all objects into garbage collector and after when the system need memory the demon clear the collector and the free the objects.
-
bq. put the all objects into garbage collector
Yes, my Underworld class has a destroy method. Can you give me an example of a garbage collector implemented in the main function?
-
You can simple delete the pointer after application is finished.
@
...
uw::world = new Underworld(userRootPath, corePath, true);MainWindow w; w.show(); int rc = a.exec(); delete uw::world; return rc;
}
@[EDIT] An explanation. The destructor is called when an object is destroyed. For the objects that are allocated on a stack it happens automatically. All QString and QApplication in your example. For the objects that are allocated on a heap using new operator it is your responsibility to delete it. Unless you use smart pointers.
-
bq. Yes, my Underworld class has a destroy method. Can you give me an example of a garbage collector implemented in the main function?
Tha garbage collector is internal in the system (if you work in java this concept is strong).
In C++ is your responsibility to delete it and the response by andreyc is correct.