Use automatic (stack) distribution whenever the function area is or the scope of a control unit, such as for , while , if , etc. inside the function - this is a good match for the life of the object is necessary. Thus, if an object owns / manages any resources, such as dynamically allocated memory, file descriptors, etc. - they will be freed during the call of the destructor, as this area remains. (Not at some unpredictable late time when the garbage collector completes).
Use only new if there is a clear need, for example:
the object needs to live longer than the function area,
transfer ownership to another code
have a container of pointers to base classes, which can then be processed polymorphically (i.e. using virtual dispatch to implement the functions of a derived class) or
especially large allocation that eats up most of the stack (your OS / process will have a "consistent" limit, usually in the range of 1-8 + megabytes)
- If this is the only reason you use dynamic allocation, and you want the lifetime of the object to be bound to a region in your function, you should use local
std::unique_ptr<> to manage the dynamic memory and ensure that it is issued no matter how you leave the scope: return , throw , break , etc. (You can also use the std::unique_ptr<> data element in class / struct to manage any memory the object belongs to.)
Mathieu Van Nevel comments below on the semantics of C ++ 11 movement - the relevance is that if you have a small control object on the stack that manages a large amount of dynamically allocated (heap) memory, moving semantics provides additional guarantees and a fine - controlled control when the control object transfers its resources to another control object belonging to another code (often calling, but potentially different container / register of objects). This transfer can avoid short-term copying / duplication of heap data. In addition, optimizing elision and return-value often allows nominally automatic / stacked variables to be constructed directly in some memory, which they ultimately are assigned / returned, rather than copied there later.
Tony delroy
source share