Reputation: 4438
I'm re-learning c++ (I have 10 years Java experience) and I'm also learning Qt in the process...
I'm used to creating objects (in Java) via:
MyObject o = new MyObject();
But when creating a QApplication in c++, the examples simply show:
QApplication app(argc, argv);
app.setOrganizationName("My Company");
app.setApplicationName("The App");
So suddenly, I have a reference to "app" and no obvious (to me) assignment to app...
Is this pattern a c++ thing or specific to Qt? What is this pattern called?
Thanks!
Upvotes: 4
Views: 3128
Reputation: 96157
Not really a Qt question but,
//You have an assignment to app
QApplication app(argc, argv);
// is just the same as
QApplication *app = new QApplication(argc, argv);
In C++ you have the choice of creating objects locally (on the stack) or with new (on the heap). Allocating it locally here makes more sense when the app object has a definite lifetime (the length of main) won't be deleted and recreated and only one exists.
One annoying feature of C++ (because of it's c heritage) is that accessing parts of the resulting object is different. If created directly you use "." app.name()
but if allocated with new you need to use 'c' pointer notation app->name()
ps. There are a few Qt specific memory features. Qt does a lot of memory management for you, eg. copy-on-write, automatic delete. In Qt you rarely have to call delete for an object - for a C++ expert these are sometimes annoying but from Java it should look more natural.
Upvotes: 7
Reputation: 2665
The variable app
is created on the stack on the line QApplication app(argc, argv);
it calls QApplication
's constructor with arguments argc
and argv
which creates QApplication
object called app
in this case.
It's not a feature specific to Qt. You can allocate any non-virtual class with constructor this way as well. Also, it works on primitives so you can do for example this:
int val(1); // Equivalent to: int val = 1;
which would create integer variable named val
with value 1.
You could allocate the QApplication object on heap using new
and use it like this:
QApplication* app = new QApplication(argc, argv); // Heap allocation
app->setOrganizationName("My Company"); // Notice the -> instead of .
app->setApplicationName("The App");
The ->
is basically a shortcut for dereferencing the pointer and using .
Allocating on the stack is usually preferable (but not always feasible), because then you do not have to care about the object's lifetime (with either some smart pointer or raw delete
), stack allocating is also usually less expensive than allocating on the heap.
Upvotes: 5