const 정확성에 대한 질문이 무작정 있습니다.C++의 Const Correctness Question
내가 싱글 톤인 클래스가 있다고 가정 해 보겠습니다. 내가 직접 내가 그것을 &을 Foo 등을 const를 푸에서이 포인터를 변환 할 수없는 오류가 발생 LoadStringIntoMap 전화를받을 경우
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));
}
로 정의됩니다. 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