У меня есть случайный вопрос о корректности 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 я получаю сообщение об ошибке, что он не может преобразовать этот указатель из сопзИ Foo Foo к &. Это имеет смысл с момента вызова функции non 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;
Спасибо, что имеет смысл, я выставляю код для singleton. Я не написал этот код, я пытаюсь его понять. – UberJumper