An easy way to avoid dynamic distribution is to use a static distribution , which roughly corresponds to the opposite dynamic distribution. However, this must be done carefully, because even with a non-threading program, you can inadvertently end up in a situation where two or more parts of the code believe that they "own" some statically distributed object. Even worse, such significant global variables (even if they are hidden as single variables or in the code below as local statics) essentially serve as central hubs for spaghetti exchange, where information causing chaos spreads freely between places you could never have imagined, completely out of your control.
So the static distribution scheme has some disadvantages & hellip ;:-)
But let & rsquo; s start there:
// Using static allocation.
To avoid the erroneous rejection of the static allocation scheme, you can provide storage on the stack using C ++ automatic allocation (automatic distribution C ++ is, by definition, a stack, LIFO distribution scheme). But that means transferring storage to a function. Then the function can return a link to the corresponding object:
But even when we decide to ignore such problems as building with side effects, etc., i.e. when we blithely assume that classes B and C are designed to work well with such a scheme, the above waste repository.If the instances of B and C are large, you can consider using C ++ objects to build objects in a previously existing repository called new location . Due to memory alignment issues, it's a little hard to do right in C ++ 03, but C ++ 11 offers better support:
#include <iostream>
Now, which of the above options would I choose?
I would choose a strictly limited, but simple and instantaneous static allocation, or I would choose automatic memory allocation, or perhaps & hellip; optimized, but somewhat complex construction of the object in place?
Answer: I would not choose any of them!
Instead of focusing on microefficiency, I would focus on clarity and correctness and, therefore, just took a hit on the performance of dynamic allocation. For correctness, I would use a smart pointer to the result of the function. If this turned out to be really slowing down, I would probably consider using a dedicated allocator of small objects.
In conclusion, no need to worry about the little things! :-)