C++/C++

(작성 중) Scoped static 과 Singleton

Elan 2022. 2. 2. 01:14

Scoped Static

C++11부터 등장한 것으로
함수의 Scope 내부에 static 속성으로 선언 되는 객체는
프로세스의 시작 ~ 종료 과정 동안 오직 한번만 초기화되므로(이때 Lazy Initialization 방식을 취함)
std::mutex나 std::call_once같은 것으로 배타적 접근을 구현할 필요가 전혀 없다.

또한 오직 하나만 존재하는 것을 보장하기 때문에
멀티 쓰레드 환경에서 호출되었다 하더라도 무조건 한번만 초기화 된다.

아래의 코드를 실행해 보면 어떻게 동작하는지 알 수 있다.

class ScopedStatic
{
public:
	ScopedStatic(int _num)
	{
		std::cout << "ScopedStatic( "<<_num<<" )" << std::endl;
		num = _num;
	}

	int num;
};

void InitOnlyOnce(int _num)
{	// Scoped Static은 프로세스의 시작~종료 동안 오직 한번만 초기화 되며, 단 하나임을 보장한다.
	// 또한 Lazy Initialization 방식으로 동작한다.(즉, InitOnlyOnce 함수가 호출되었을 때 초기화 된다)
    // 때문에 ScopedStatic이 한번 초기화 된 후일지라도 Scoped Static코드를 지날 때 약간의 오버로드가 존재할 수 있음
	static ScopedStatic ss(_num);
}

int main()
{
	std::cout << "program starts" << std::endl;
	std::thread t1(InitOnlyOnce,3);
	std::thread t2(InitOnlyOnce,2);

	t1.join();
	t2.join();
}

 

Scoped static을 이용하면 Singleton 패턴을 간단하게 구현할 수 있다.

class Singleton
{
public:
	static Singleton& GetInstance()
    {
    	static Singleton obj; // scoped static이기 때문에 유일 객체임을 보장
        return obj;
	}
private:
	Singleton() = defautl;
    // 완전한 싱글턴 패턴을 구현하기 위해 Copy/Move Constructor &  Assignment를 삭제
    Singleton( const Singleton & ) = delete;
    Singleton( Singleton && ) = delete;
    Singleton& operator=( const Singleton& ) = delete;
    Singleton& operator=( Singleton && ) = delete;
}

 

 

참고로 C++에서는 Singleton을 구현할 수 있는 방법이 여러가지이다.