There are several levels in the answers.
First, variables can be declared in several ways:
- As local variables (inside a function or as members of a class). Examples:
int i or int i = 42 . They have an automatic storage duration (these examples are technically shortened for auto int i or auto int i = 42 , although the auto keyword is almost never used. This means that these variables will be automatically freed when they go out of scope. Their destructor is guaranteed will be called (regardless of how you leave the scope, whether the function is returned or throws an exception, their destructor will be called when they leave the scope, and then the freed memory will be rim) local variables declared in this way are allocated on the stack. - Static variables (with the
static implying a static storage duration, unlike the automatic one shown above). They simply remain throughout the program and therefore do not need to be freed. - on the heap, with dynamic allocation (
new int or new int(42) ). They need to be freed manually by calling delete .
So, at the lowest level, you just need to maintain symmetry. If something was highlighted using new , release it with delete, malloc is freed by free , and new [] by delete [] `. And variables declared without any of them are automatically processed and should not be manually released.
Now, to simplify memory management, RAII is usually used. The method is based on the observation that only dynamically allocated objects should be manually released, and local variables give you a very convenient hook for implementing custom actions when a local variable goes out of scope.
So, dynamic allocation is completed inside a separate class, which can be allocated as a local object on the stack. He can create any dynamic distributions that you need in his constructor, and his destructor clears it with the necessary delete calls.
This means that you essentially never need to call delete in the top-level code. It will almost always be hidden behind the destructor of the RAII object. new also become rare, but are still used with smart pointers (for example: boost::shared_ptr<int>(new int(42)) , which dynamically allocates an integer and then passes it to the smart pointer, which takes care of his possession, and automatically cleans it.
source share