单例类滥用,c ++ - 需要解释

时间:2014-12-06 00:22:39

标签: c++

我刚刚遇到了我认为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 ?!

为什么我能做到这一点,我做错了什么?或者这不是做错什么的情况,我只是误用了一些记忆并得到了未定义的行为' ?因为这是我的第一次尝试。

有趣的部分是 - 如果我不使用在该方法的类头中定义的变量,则应用程序有效。

1 个答案:

答案 0 :(得分:0)

通过nullpointer调用具有未定义的行为。

任何事情都可能发生。

相关问题