C ++ stack vs heap allocation

I was wondering when should I allocate a class on a stack in C ++? I have strong Java experience, and in Java all classes are allocated on the heap using the new keyword. In C ++, I can choose between stack and heap allocation, but now that smart pointers are introduced, it makes sense to select everything that doesn't transfer ownership with std::unique_ptr .

I cannot think of any cases where it would be necessary or better to use stack distribution. Maybe for some kind of optimization in embedded systems?

+7
c ++ memory-management
source share
2 answers

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.

+14
source share

In a large code base, we use stack distribution for simple structural objects, while for more complex classes (including polymorphism, memory ownership, etc.) we always use dynamic allocation.

+1
source share

All Articles