반응형
아래의 코드처럼 복사 생성자, 복사 대입 연산자를 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;
}
반응형
'C and C++' 카테고리의 다른 글
[C/C++] for문에서 전위증가 후위증가 차이점 (0) | 2021.02.06 |
---|---|
[C++][STL] vector의 메모리(capacity) 완벽하게 제거하기 feat. swap (0) | 2021.02.06 |
[C++][STL] vector for문 올바로 사용하기 (0) | 2021.02.06 |
[C] C에서 생성자 소멸자 흉내기 (0) | 2020.10.11 |
[C++][STL] STL을 활용하여 상한값 하한값 단순화 (0) | 2020.05.03 |