我有一个关于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