类初始化问题
class initialization problem
程序工作正常,但内存验证器报告错误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()函数在我需要的任何地方访问实例
相关文章:
- C++转换参数初始化问题
- 运行时C++数组初始化问题
- wxWidgets 拖放文件事件处理程序初始化问题(无效static_cast)
- C++初始化具有 int 0 问题的unique_ptr
- 使用初始化列表填充C++中的多维结构数组时出现问题
- 它解决了什么问题,对于非真空初始化,生命周期在初始化之前就开始了
- 在构造函数 c++ 中初始化属性时出现问题
- 我是否需要在虚拟继承类的构造函数中初始化基类以解决菱形继承问题?
- (2 问题)"类"类型重新定义(即使 #pragma 一次),以及静态函数内的静态成员对象初始化?
- shared_ptr类的向量的向量初始化问题
- public:静态常量字符串声明/初始化问题
- 初始化与类类型相同的静态成员(静态初始化顺序问题)
- 使用 true 初始化布尔数组时出现问题
- 为什么C++中的大括号初始化可以解决STL容器的初始化问题
- 程序在没有输入的情况下退出,它有基本的,驱动的类属性初始化问题
- C++中构造函数的对象初始化出现问题
- 初始化com对象的问题
- 初始化多个纹理 OpenGL、SDL C++ 时出现问题
- 共享库中 __attribute__((构造函数)) 的全局/静态变量初始化问题
- 理解向量初始化时出现问题