单例类误用,需要解释

singleton class misuse, explanation needed

本文关键字:解释 单例类      更新时间:2023-10-16

我刚刚遇到了我在 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 调用具有未定义的行为。

任何事情或什么都不可能发生。