0
我只是碰到了我因子評分是不是在C可能++(我正在學習吧)單例類濫用,C++ - 解釋需要
我稱爲非靜態函數沒有初始化類(單例類)對象或跆拳道來到happend,我不是抓住它,這是== 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.
}
現在accesing此singleton類的方法,無需破壞的正確方法它是:
(&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 ?!
爲什麼我能夠做到這一點,我做錯了什麼?或者這不是做任何錯誤的情況,我只是誤用了一些內存,並得到'未定義的行爲'?因爲這是我第一次嘗試。
有趣的部分是 - 應用程序工作,如果我不使用該方法的類標題中定義的變量。
什麼也沒有定義,你不覺得嗎?所以只需使用靜態的LightsLogic * logicofligths;我訪問類錯誤?爲什麼它讓我這麼做? :| – Tomas 2014-12-06 00:29:46
無法限制指針上允許的操作。即使已知,指針的值也不會被認爲是wrt。彙編。但是如果你提高警告級別,編譯器可以*警告*。我會嘗試。 – 2014-12-06 00:33:40