C and C++
[C++] 싱글톤 생성 팁
개발새발
2022. 8. 15. 17:38
반응형
아래의 코드처럼 복사 생성자, 복사 대입 연산자를 delete하여 싱글톤의 품질을 높일 수 있다.
#include <iostream>
using namespace std;
class Singleton
{
public:
Singleton(const Singleton&) = delete; // 복사 생성자(copy constructor) 금지
Singleton& operator=(const Singleton&) = delete; // 복사 대입 연산자(copy assignment operator) 금지
static Singleton& getInstance()
{
static Singleton instance; // 늦은 초기화 + 쓰레드 세이프
return instance;
}
private:
Singleton() { cout<<"constructor"<<endl; }
~Singleton() { cout<<"destructor"<<endl; }
};
int main(void)
{
Singleton& testSingleton = Singleton::getInstance();
return 0;
}
반응형