The beauty of C ++ is that you have explicit control over when things are created and when things are destroyed. Do it right and you won’t have problems with memory leaks, etc.
Depending on your environment, you can create objects on the stack, or you may want to dynamically allocate (to create them on the heap, "heap" is a heap in quotation marks, because this is an excessive term, but so far good enough).
Foo x; // created on the stack - is automatically destroyed when the program exits from this block of code in which it was created.
Foo * y = new Foo; // created on the heap - its OK to go through this round, since you control its destroyed
Whenever you use the "new", you should use the appropriate version of the uninstall ... somewhere, somehow. If you use new to initialize a smart pointer, for example:
std :: auto_ptr x = new Foo;
In fact, you are creating two elements. The auto_ptr instance and the Foo instance. auto_ptr is created on the stack, Foo on the heap.
When the stack is "unwound", it is automatically called delete in this instance of Foo. Automatic cleaning for you.
So, as a general rule, use the stack version whenever possible / practical. In most cases, it will be faster.
source share