How to profile your code for memory consumption

insert image description here
insert image description here

object life cycle

What is the difference between the following two statements that create objects?
For Object myObject;, the object is created on the stack, and its characteristic is that it will be automatically destroyed after leaving the scope. As for new Object(), it will dynamically create an object on the heap. Its characteristic is that even if it leaves the scope, the object will always exist, unless you manually release (delete) it, otherwise there will be a memory leak.

Therefore, in order to prolong the life cycle of the object, the object is generally created by the new method, and the object is deleted by the delete method. Deleting the object means deleting the memory space occupied by the object.

When should I use new?

You need to extend the object lifetime. It means that you want to always use a variable at a certain address location, not a copy of it. For the latter, we should use the syntax of Object myObject;.
You need a lot of memory. Everyone knows that the stack space is much smaller than the heap space.
When you really want to use dynamic memory allocation, we should use smart pointers or other RAII techniques to manage this part of the resource.

Knowing how dynamic memory works in C++ is essential to being a good C++ programmer. The memory in a C++ program is divided into two parts:
Stack: All variables declared inside a function will occupy stack memory.
Heap: This is unused memory in the program, where

Guess you like

Origin blog.csdn.net/qq_21950671/article/details/131655307