简体   繁体   中英

Design for memory allocators scope

I have been reading different articles on memory management in preparing for how I want my architecture to work, with my biggest worries on how the allocators will be used, created and handled throughout the code base. One of the issues is that my design always has the allocator(s) at a global scope, since I don't have a typical singleton design to contain the allocators, they have no real place to live. I would like to avoid using globals for this due to all the issues typical had with using globals.

This lead me to the design of having something such as

void* operator new(size_t size, uint32_t type)
{
    return gAllocator.Alloc(size, type);
 }

This would then lead to having just the new definition in a header file, with the declaration in a .cpp. This .cpp file would then have the gAllocator , only in the .cpp file (and can be accessed in place else except for the new call.

If my design would to be like this, would the gAllocator still be a global variable, if not, what type of variable would it be considered? What if it was in the scope of just a namespace?

It seems a plain global is just what you want. For review, in C++ a global (or singleton) should be a local static variable in an inline function.

class myAllocator {
public:
    static myAllocator &getDefaultInstance() {
        static myAllocator theInstance( parameters );
        return theInstance;
    }
};

This way, the object is initialized the first time it's used. If you use a typical header declaration + .cpp definition, the order of initialization with respect to other globals is undefined, with possible unpredictable consequences. (The "static initialization order fiasco.")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM