我一直在閱讀關於全局變量和它們有多糟糕,但由於這個原因我被困在一個地方。我將非常詳細地說明在這種情況下是否應該使用全局變量。我應該使用全局變量嗎?
我工作的一個遊戲引擎。而我的引擎由很多經理組成。經理做某些任務 - 它們存儲資源,加載它們,更新他們等
我已經做了我所有的經理一個單身,因爲有很多類和函數需要對它們的訪問。我正在考慮取消單身人士,但我不知道我怎麼能拿到這個單身人士,並接觸到這些經理。
這裏是什麼,我想告訴一個例子(在英語,對不起IM壞):
Singleton.h
template<class T> class Singleton {
private:
Singleton(const Singleton&);
const Singleton& operator=(const Singleton&);
protected:
Singleton() { instance = static_cast<T*>(this); }
virtual ~Singleton() {}
protected:
static T * instance;
public:
static T &Instance() {
return *instance;
}
};
ScriptManager.h
class ScriptManager : public Singleton<ScriptManager> {
public:
virtual void runLine(const String &line)=0;
virtual void runFile(const String &file)=0;
};
PythonScriptManager。 CPP
class PythonScriptManager : public ScriptManager {
public:
PythonScriptManager() { Py_Initialize(); }
~PythonScriptManager() { Py_Finalize(); }
void runFile(const String &file) {
FILE * fp = fopen(file.c_str(), "r");
PyRun_SimpleFile(fp, file.c_str());
fclose(fp);
fp=0;
}
void runLine(const String &line) {
PyRun_SimpleString(line.c_str());
}
};
實體ScriptComponent
#include <CoreIncludes.h>
#include <ScriptManager.h>
#include <ScriptComponent.h>
void update() {
ScriptManager::Instance().runFile("test_script.script");
//i know its not a good idea to open the stream on every frame but thats not the main concern right now.
}
應用
int main(int argc, const char * argv) {
Application * app = new Application(argc, argv);
ScriptManager * script_manager = new PythonScriptManager;
//all other managers
return app->run();
}
正如你看到的,我甚至不包括在其中贏得了我一些編譯時間我ScriptComponent.cpp文件的文件上面。我怎樣才能得到這樣一個沒有全局變量的結果,這將使它易於整合爲一個。單例不是線程安全的,但添加線程不需要很長時間。
我希望我可以解釋這個問題。
由於提前,
卡西姆Gasimzada
沒有什麼神祕的。避免使用全局變量的方法是不擁有它們。如果函數A需要訪問對象B,並且B不是全局的,那麼B已經作爲參數傳遞給A.這就是如果你沒有全局變量的話。將必要的對象作爲函數(或構造函數)參數傳遞。 – jalf
由於我無法評論你的帖子,我會在這裏發表評論。 @jalf我真的明白,全局變量是不好的,另一種可靠的解決方案是將值傳遞給函數或c'tors的參數。但在這種情況下,我遇到了兩個大問題?從那裏我得到這些經理(他們實際上只是包裝,使編碼更容易)? @Dave說要製作'執行'對象(讓它稱爲引擎),它存儲所有這些對象並將引用傳遞給函數或c'tor。但我怎麼做呢?我想讓它更輕鬆,更清潔。 – Gasim
其實從來沒有。我找到了一種方法:)我想要使用單例的唯一原因是因爲我將不得不在每個源文件中只有很少的依賴關係,但現在我找到了一種方法:)感謝各位的幫助!現在重新開始工作。 – Gasim