我正在寫一個Cocos2D-X遊戲,其中玩家,敵人和其他角色將他們的屬性存儲在CCMutableDictionary
中,這是std::map<std::string, CCObject*>
的裝飾類。字典中的值可以通過CCMutableDictionary::objectForKey(const std::string& key)
方法訪問。現在在頭文件中執行const std :: string的正確方法?
,通過我的很多.cpp文件包含的頭文件,我有幾個const char * const
串在字典訪問值,如:
// in Constants.h
const char* const kAttributeX = "x";
const char* const kAttributeY = "y";
// in a .cpp file
CCObject* x = someDictionary->objectForKey(kAttributeX);
所以,如果指正我錯了,但是std::string
的拷貝構造函數正在被調用,並且每當我使用const char* const
調用上述objectForKey
方法中的一個時,臨時std::string
就在堆棧上,對吧?
如果是這樣,我覺得如果這些常量屬性鍵已經是std::string
對象,那麼運行效率會更高。但我該怎麼做,權利的方式?
定義他們在Constants.h文件中像下面編譯罰款,但我有一種感覺,有些事情是不正確的:
// in Constants.h
const std::string kAttributeX = "x";
const std::string kAttributeY = "y";
我的道歉,如果這個問題已經問。我似乎無法找到我在StackOverflow上尋找的確切答案。
因此,如果字符串是在.cpp文件中定義的,它們何時實際實例化? – 2012-04-18 03:39:04
@NatWeiss它們將與所有其他全局變量一起實例化。 – 2012-04-18 18:26:34
多次定義的變量問題是否適用於「const char * const」?我很確定它沒有,但我不明白爲什麼。是什麼賦予「const char * const」在單個位置定義的特權,包括其值(更好,IMO,特別是維護方面)? – Brent212 2015-02-06 23:09:47