Hello, I am writing an application in C ++ (Qt), which works from the database and during my entire work I had a question in what situations, when and where to allocate memory for a variable? For example, I have a form that uses one common request, I define a variable for this request, and the question is where is it better to allocate it in a stack or in a heap?

namespace Ui { class ClassesForm; } class ClassesForm : public QMainWindow { Q_OBJECT public: ... private: ... QString selectedClass; // или QString *selectedClass и в конструкторе //выделить память под нее? }; 

And for example, there is a function in which another request is used, which is not used anywhere else except this form, in this case, where to select it?

 void ClassesForm::changeDescriptionOfClass() { QString query; //Или выделять память? ... } 

I would like to get a clear answer, not only about these examples, but also a generally distinct question when, what and where is better to use ...

  • It definitely doesn’t make sense to dynamically allocate memory. - Rikitikitavi

1 answer 1

It makes no sense to dynamically allocate memory, only if for you it is not a critical parameter. Everything is well described here about dynamic memory allocation - https://habrahabr.ru/company/aligntechnology/blog/283352/

The main idea: try to remove the new and delete calls from the client code. They are needed only in exceptional cases, and these cases require exceptional attention. For example, this is the creation of your own container or memory manager.