sI’m on Windows and I’m building a C++ project with VS2008. I’m trying to replace new/delete/malloc/free etc. Which is working i.e. my replacements are getting called.
However my replacement allocator needs to be initialised. I have done this thus far by defining it as a global variable in a .cpp file with the #pragma init_seg(lib) defined inside it.
This worked up until recently when std::locale started to get initialised which was calling new before my allocator was getting initialised. So I nervously moved my allocator’s global variable to the compiler segment ie #pragma init_seg(compiler).
This worked for a bit and then I decided to override malloc. Now I get a malloc call in __crtGetStringTypeA_stat in _tmainCRTStartup which is before even the global vars in the compiler segment have been initialised.
Is there any way to get my variable be instantiated before the CRT start up. The only thing I can think of is rebuilding my crt lib and trying some how to insert my initialisation code in there some where. I presume there must be a crt clean up function as well?
Is there an easier route to this and/or something obvious I’m missing here?
You are using a
static storage durationobject.But you are having problems with the order of initialization.
To solve this use a static storage duration object that is defined within a function scope.
Now your versions of new/delete/ etc can get a reference to the allocator by calling getAllocator(). This will guarantee that the object is correctly initialized (assuming MyAllocator has the correct constructor).