类初始化问题

class initialization problem

本文关键字:问题 初始化      更新时间:2023-10-16

程序工作正常,但内存验证器报告错误UNINITIALIZED READ在线CProfiles配置文件;

在CProfiles主体之外定义类CProfiles是一个不好的编程实践吗?

下面是我的代码:内部profiles.cpp
#include "profiles.h"
CProfiles profile;  // Here it reports the problem
KeyProfile* keyProfile=&profile;    // keyProfile is later used in other classes
//-------------------------------------------------------------
CProfiles::CProfiles():forceDialog(0)
{
      oldName="";
}
int CProfiles::Init()
{   
     _chdir(PROFILES_PATH);
}
CProfiles::~CProfiles()
{
}
在profiles.h

#define PROFILES_PATH           "Profiles"  
#include "KeyProfile.h"
class CProfiles: public KeyProfile
{
    public: 
       CProfiles();
       ~CProfiles();
       int Init();
       bool forceDialog;
       string oldName;
};
extern CProfiles profile; 

KeyProfile.h

    public:
   virtual UINT GetKeyUp()      { return DIK_UP; }
   virtual UINT GetKeyDown()    { return DIK_DOWN; }
   virtual UINT GetKeyLeft()    { return DIK_LEFT; }
   virtual UINT GetKeyRight()   { return DIK_RIGHT; }
   virtual UINT GetKeyAction()  { return DIK_RETURN; }
   virtual UINT GetKeyCancel()  { return DIK_RCONTROL; }
       virtual UINT GetKeyEsc() { return DIK_ESCAPE; }
   KeyProfile(void){};
   virtual ~KeyProfile(void){};
    };
    extern KeyProfile* keyProfile;

您正在使用的代码分析器正在抱怨,因为您已经在CProfiles profiles;中实例化了一个自动对象extern关键字告诉编译器,您正在设置的对象外部将在其他地方创建,因此链接器稍后将找到该符号,并使其全部工作。代码分析器提醒您可能忘记初始化对象了。

更新:实际上我发现了一个问题。这是静态初始化顺序的惨败。有关该问题的更多信息,请参见:构造函数——如何防止"静态初始化顺序惨败"?

下面是我代码中的解决方案:

// in profiles.cpp
//CProfiles profile; // Insted this, I access the instance through the profile() function
CProfiles& profile()    
{
    static CProfiles* ans = new CProfiles();
    return *ans;
}
KeyProfile* keyProfile=profile();

我通过profile()函数在我需要的任何地方访问实例