C++ singleton pattern 구현

luckyhan studio·2021년 5월 20일

Singleton pattern은 정말 자주 쓰이는 패턴이다.
구현은 쉽다고 하면 쉽고 어렵다고 하면 어려운 듯 하다. 특히 C++ 에서 singleton 을 구현하려면 thread-safe 한지 아닌지도 신경 써야 한다. 뭐 물론 내 애플리케이션이 multi thread를 사용하지 않는다면 상관은 없다.

C++에서 아래와 같이 singleton을 구현하면 thread-safe하다.

hpp

class Singleton
{
public:
	Singleton(const Singleton&) = delete;
	Singleton& operator=(const Singleton&) = delete;
	~Singleton(){};
	static Singleton& getInstance();
private:
	Singleton(){};
};

cpp

#include "Singleton.hpp"


Singleton& Singleton::getInstance(){
	static Singleton instance;
	return instance;
}

특히 주의할 점은 static으로 getInstance() 함수 내에서 변수를 정의하므로 getInstance의 정의는 반드시 cpp에 구현되야 한다. 그렇지 않으면 multiply defined 와 같은 compiler 에러가 발생할 것이다.

profile
열심히 사는 그냥 개발자

0개의 댓글