I have a random question about const correctness.
Lets say i have a class that is a singleton.
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;
};
The functions are defined as such
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));
}
If i directly get call LoadStringIntoMap i get an error that it cannot convert this pointer from const Foo to Foo &. Which makes sense since your calling a non const function from within a const function. But why is this not an issue when calling the singleton, and doing modification through that.
Is this just really unsafe?
This is what singleton is defined as:
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;