简体   繁体   中英

Global const variables not assigned when constructor is executed

MY_GLOBAL_CONST is not assigned when I try to use it in ProblemClass::ProblemClass() . Why? How to fix that? I am working on an old VC6 MFC project.

SomeClass.h

#include "ProblemClass.h"
class SomeClass  
{
private:
    ProblemClass m_problemClass; //created on the heap

public:
    SomeClass();
    ~SomeClass();
}

ProblemClass.h

class ProblemClass
{
public:
    ProblemClass();
    ~ProblemClass();
}

ProblemClass.cpp

#include "ProblemClass.h"
const CString MY_GLOBAL_CONST = _T("User");//Also tried to put that line in ProblemClass.h without luck
ProblemClass::ProblemClass()
{
    CString foo = MY_GLOBAL_CONST; //MFC-Runtime assertion fails, MY_GLOBAL_CONST  is not assigned yet 
}
ProblemClass::~ProblemClass(){}

Update:

After some further investigation I can confirm that SomeClass is also instantiated in a global context. So, Paul Sanders is absolutely right by saying "happening here is two global initialisers being executed in the wrong order" .

Try replacing:

const CString MY_GLOBAL_CONST = _T("User");

with:

const TCHAR MY_GLOBAL_CONST [] = _T("User");

The latter construct doesn't require any run-time initialisation and MY_GLOBAL_CONST can therefore be relied upon in other initialisation code (because what is surely happening here is two global initialisers being executed in the wrong order).

I looks like you missed the static keyword with you declaration. My recipe for gloabl variables which need to be initialized outside of the class.

Header File

class ProblemClass
{
public:
    ProblemClass();
    ~ProblemClass();

private:
    static const CString MY_GLOBAL_CONST; // declaration in the header file
}

Source File

const CString ProblemClass::MY_GLOBAL_CONST = _T("HELLO_WORLD"); // Initialization here outside of class

ProblemClass::ProblemClass()
{
    CString foo = MY_GLOBAL_CONST; //MFC-Runtime assertion fails, MY_GLOBAL_CONST  is not assigned yet 
}

// everything else

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