简体   繁体   中英

Static variable in template class function overwritten by global static variable

I have a static variable in a template class function like this :

template<class T>
struct builder 
{
    static T* buildOrGet() 
    { 
        static T* built = nullptr;
        if(built == nullptr) built = new T;
        return built;
    }
};

and somewhere else in the code a global variable with a constructor.

static SomeClass global_var;

At first I didn't know what happened but the built variable was corrupted at a certain point of the program for no reason. Then, I added a 4-bytes data breakpoint in visual studio on &built to see who crushed its memory after built = new T; , and in fact it is during the C++ dynamic-initializer when initializing members of global_var , in the SomeClass constructor. The code is in a dll, auto loaded by an exe depending on it. It is like global_var memory overlaps built memory, which is very weird.

I really don't understand why and how this could happen except a bug in Visual Studio 2015, can you help me ?

I found the solution : In fact I have multiple global_var with the same name in different translation units of my dll but they don't have the same type (let's say another has int type).

In this case (which is weird to me because they are 'static'), the linker just keep one and use the same memory for all the variables (it kept here the int one).

This is where it goes wrong... The SomeClass constructor is still called for the global_var I mentioned above but its memory is not sizeof(SomeClass) , but sizeof(int) , and this is where the overflow happens .

To me it's a bug, because the linker should have noticed me about these homonymous variables with different types or/and should have avoid to call a constructor on a variable which doesn't match the constructed memory.

The solution is : never declare two static variable with the same name in different translation units, only one will survive and you cannot guess which one.

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