According to Google C++ Style Guide - Static and Global Variables,
Decision on Destructions
...
Therefore, we only allow objects with static storage duration if they are trivially destructible.Common Patterns
...
- Maps, sets, and other dynamic containers: ... If you do really prefer a dynamic container from the standard library, consider using a function-local static pointer, as described below.
- If all else fails, you can create an object dynamically and never delete it by using a function-local static pointer or reference (e.g.,
static const auto& impl = *new T(args...);
).
As far as I know, dynamically allocated objects will never be freed.
OS will free every unfreed object when the program ends, but this isn't the correct way.
Why not deleting a dynamically allocated object is a selectable option?
Because of this:
In short, not deallocating memory is a problem because that can cause unnecessary memory use in form of memory leaks. Unnecessary use of memory doesn't matter to a program that is no longer running, so it isn't a problem in this case.
Note that if you do follow this style, then you may find that some memory analysers report the lack of deallocation as a memory leak which may be difficult to distinguish from unintentional memory leaks.
Aside from the (non-)problem of memory leak, to explain why this might be a preferable option, this style avoids some problems with Static Initialisation Order Fiasco without requiring the Nifty Counter Idiom. As an additional bonus, it likely makes the shutdown of the program a bit faster.