The relative order of initialization of non-local static objects

Refer to Effective C++ 3rd item 4.

The Relative order of initialization of non-local static objects defined in different translation units is undefined.

main.cpp
--------------------------
testVar var;

int _tmain(int argc, _TCHAR* argv[])
{

     int t[16];
   
    memcpy( t, var.getVar(), 16 * sizeof(int) );
    return 0;
}


The t will be set [ 0, 0, 0,...... ]. It is wrong, I have set the t to g_identity. I must occur the relative order problem.  Below is the original source code.

testVar.h
--------------------------
template
class testVar
{
private:
    Type var[16];
    static const testVar g_identity;
};


testVar.inl
-----------------------
template const testVar testVar::g_identity( 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 );

template
testVar::testVar()
{
    setIdentity();
}

template
void testVar::setIdentity()
{
    memcpy( var, g_identity.getVar(), 16 * sizeof(Type) );
}


I replaced direct access non-local static variable - g_identity with call to function

testVar.h
--------------------------
template
class testVar
{


private:
    Type var[16];
     const testVar& getIdentity();
};

testVar.inl
-----------------------
template
 const testVar& testVar::getIdentity()
{
    static testVar g_identity( 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 );

    return g_identity;
}


template
void testVar::setIdentity()
{
   // testVar t;

    memcpy( var, getIdentity().getVar(), 16 * sizeof(Type) );
}

main.cpp
--------------------------
testVar var;
{

     int t[16];
   
    memcpy( t, var.getVar(), 16 * sizeof(int) );
    return 0;
}

Finally, The t will return [ 0,1,2,3,4,....]. It is good!!


* Avoid initialization order problems across translation units by replacing non-local static objects with local static objects.
Translation: the source file includes the used header files.

Reference:
http://fcamel-life.blogspot.com/2011/10/c-non-static.html

Comments

Popular posts from this blog

Drawing textured cube with Vulkan on Android

glTF loader for Android Vulkan

C++ unit testing & CI integration in GitHub (I/2)