Qt Training - Creating QApplication

I retrain C ++ (I have 10 years of Java experience) and I also learn Qt in the process ...

I use to create objects (in Java) with:

MyObject o = new MyObject(); 

But when creating QApplication in C ++, the examples just show:

 QApplication app(argc, argv); app.setOrganizationName("My Company"); app.setApplicationName("The App"); 

So, I have a link to the "application" and there is no obvious (for me) destination for the application ...

Is this C ++ template or Qt specific? What is called this template?

Thanks!

+4
source share
2 answers

Not 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 a new one (on the heap). Selecting it locally here makes sense when the application object has a certain lifetime (the length of the main one) will not be deleted and recreated, but only one exists.

One of the annoying features of C ++ (due to this c-legacy) is that access to parts of the resulting object is different. If you created directly, you use ".". app.name() , but if highlighted with a new one, you need to use the c pointer app->name()

ps. There are several Qt specific memory functions . Qt does a lot of memory management for you, for example. copy to write, automatic deletion. In Qt, you rarely have to call delete for an object - for an expert in C ++ this is sometimes annoying, but from Java it should look more natural.

+6
source

The app variable is created on the stack in the QApplication app(argc, argv); line QApplication app(argc, argv); , it invokes the QApplication constructor with arguments argc and argv , which in this case creates a QApplication object called app .

This is not a feature of Qt. You can also select any non-virtual class using the constructor. In addition, it works with primitives, so you can do this, for example:

 int val(1); // Equivalent to: int val = 1; 

which would create an integer variable named val with a value of 1.

You can allocate a QApplication object on the heap with new and use it as follows:

 QApplication* app = new QApplication(argc, argv); // Heap allocation app->setOrganizationName("My Company"); // Notice the -> instead of . app->setApplicationName("The App"); 

-> is basically a shortcut for dereferencing a pointer and using it .

Allocation on the stack is usually preferable (but not always possible), because then you do not need to worry about the lifetime of the object (using any smart pointer or raw delete ), stack allocation is also usually less expensive than allocating a heap.

+5
source

Source: https://habr.com/ru/post/1338453/


All Articles