单例类误用,需要解释
singleton class misuse, explanation needed
我刚刚遇到了我在 c++ 中无法实现的东西(我正在学习它)
我在没有初始化类(单例类)对象或 wtf 的情况下调用了一个非静态函数,我没有掌握它,这是 == NULL,我这样做的方式是 -
我的单例类示例:
class LightsLogic {
public:
void LightsLogic::request_color_shift_group_after_x_msecs(blabla);
int current_used_chase_list = 0;
// ALL THE SINGLETON CLASS THING BELOW
private:
LightsLogic() { // CONSTRUCTOR HERE !
};
LightsLogic(LightsLogic const&); // Don't Implement. // SINGLETON
void operator=(LightsLogic const&); // Don't implement // SINGLETON
public:
static LightsLogic& getInstance() // return reference. // SINGLETON
{
static LightsLogic instance;
return instance;
}
};
所以我在某处定义:
static LightsLogic* logicofligths;
然后我从这个类调用了方法
logicofligths->request_color_shift_group_after_x_msecs(blabla);
现在发生的事情是 - 此方法使用变量:
void LightsLogic::request_color_shift_group_after_x_msecs(blabla) {
current_used_chase_list; // i am doing something with this variable
//but since this variable was defined and initialized in class header
// and this == null, this method CANT acces this variable ?! but it thinks it can ?!
//we do get a crash saying: First-chance exception at 0x013F5E8B in myexe.exe: 0xC0000005: Access violation reading location 0x00028D48.
// and if we would use this check before accesing the variable :
if (this == NULL) {
report("this is null");
return;
}
//this would prevent the crash.
}
现在,在不破坏它的情况下访问此单例类的方法的正确方法是:
(&LightsLogic::getInstance())->request_color_shift_group_after_x_msecs(blabla);
//i know i could just use LightsLogic::getInstance(). but that im using for accesing variables, more clear for me and compiler should fix this misery on compile ?!
为什么我能够这样做,我做错了什么?或者这不是做错任何事的情况,我只是滥用了一些记忆并得到了"未定义的行为"?因为那是我第一次被选中。
有趣的是 - 如果我不使用该方法的类标头中定义的变量,应用程序就可以工作。
通过 nullpointer 调用具有未定义的行为。
任何事情或什么都不可能发生。
相关文章:
- C++ 实现模板单例类时出现链接错误
- 具有非默认构造函数的单例类
- 单例类析构函数无法清理 (SDL_Quit) MinGW
- 如何在单例类中管理变量状态?
- 访问单例类C++时出现问题
- 基于 IOKit 的 kext 驱动程序中的单例类
- 指向抽象模板单例类的指针向量C++?
- C++在单例类中创建类实例时遇到困难
- 如果我这样写,我的单例类会导致什么错误
- 这是一个有效的单例类吗?
- 函数内具有静态变量的单例类(迈耶实现)
- 继承的模板化单例类 c++ 中未定义的构造函数
- 为什么调用单例类 Qt 消息处理程序成员函数会出现错误:缺少参数列表
- C++:单例类设计(错误:未解析的外部符号)
- 构造函数在不同线程中的静态单例类上调用两次
- 如何在自定义单例类中使用log4cplus
- 为什么在C 中创建单例类创建期间静态函数参考静态变量
- 如何在静态单例类中以编程方式从exec方法返回
- 为什么在单例类中私有析构函数
- 单例类误用,需要解释