我有一個關於const正確性的隨機問題。Const正確性問題C++
可以說我有一個單身人士的班級。
class Foo : public Singleton<Foo>
{
friend class Singleton<Foo>;
public:
std::wstring GetOrSet(const int id) const;
private:
Foo();
~Foo();
void LoadStringIntoMap(const int id, const std::wstring &msg);
std::map<int, std::wstring> strMap;
};
的功能被定義爲這樣
std::wstring Foo::GetOrSet(const int stringId) const
{
if (strMap.find(stringId) == strMap.end())
{
Foo::GetInstance()->LoadStringIntoMap(stringId, std::wstring(L"HELLO WORLD222"));
}
std::map<int, std::wstring>::const_iterator retStr = strMap.find(stringId);
return retStr->second;
}
void Foo::LoadStringIntoMap(const int stringId, const std::wstring &msg)
{
strMap.insert(std::pair<int, std::wstring>(stringId, msg));
}
如果我直接拿到致電LoadStringIntoMap我得到一個錯誤,它無法this指針從常量富轉換爲foo &。這是有道理的,因爲你在const函數內調用非const函數。但是,爲什麼在調用單例時,這並不是一個問題,並通過它進行修改。
這是不是真的不安全?
這是單身的定義是:
template <typename T> class Singleton
{
protected:
Singleton() {};
~Singleton() {};
public:
static T *GetInstance()
{
return (static_cast<T*> (m_This));
}
static void Destroy()
{
if(m_This != NULL)
delete m_This;
}
static void CreateInstance()
{
m_This = GetInstance();
if (m_This == NULL)
{
m_This = new T;
}
}
private:
// Unique instance
static T *m_This;
};
template <typename T> T *Singleton<T>::m_This = NULL;
由於這是有道理的,我把代碼爲單身。我沒有寫這個代碼,我試圖理解它。 – UberJumper 2009-10-12 16:45:57