This is one of the basics in C ++.
Dynamic allocation
In your case, memory allocation and the subsequent constructor call for Z
will happen on new
:
Z* z = new Z();
The opposite part for destroying and freeing memory will happen on delete
:
delete z;
But since your code does not have it, memory will never free, plus you lose the Z
pointer, which does not have the ability to free an object in the future. This is a typical memory leak.
Declaration
On the other hand, if you declare an object as follows:
Z z;
The memory allocation and constructor will be called immediately right here at the point of declaration, and when the object of the existence of the object is completed (i.e. at the end of the function), the destructor will be called automatically and the memory will be freed.
Dynamic allocation and declaration
I will not enter into the debate about what is better and what is not, but rather will provide an excerpt from one of the articles, which is given below:
Unlike ads that load data into the program data segment, dynamic allocation creates a new usable space in STACK programs (the RAM area specially allocated for this program).
FYI: Stack = Performance , but not always the best solution .
References
For your pleasure: tic tac sock .
source share