티스토리 뷰
흔히 쉽게 사용하는 디자인패턴 singleton 패턴과 객체의 복사를 방지하는 noncopyable전략.
이 두가지는 boost에서 이미 손쉽게 사용할 수 있도록 지원하고 있습니다.
우선 boost가 소스가 있어야 하며 링크되어 있어야합니다.
linux 기준으로 boost는 apt를 이용하여 쉽게 설치가 가능하며 cmake에서 이를 바로 사용할 수 있도록 지원하고 있습니다.
install : sudo apt-get install libboost-all-dev
cmake : https://gist.github.com/PuppyRush/59ae3c26ee4f68f76c0f5305b3a4526d
그런 후 소스상으로 다음과 같이 구현합니다.
// | |
// Created by chaed on 19. 2. 24. | |
// | |
#ifndef SDL2_TETRIS_SERVER_PLAYERMANAGER_H | |
#define SDL2_TETRIS_SERVER_PLAYERMANAGER_H | |
#include <boost/noncopyable.hpp> | |
#include <boost/serialization/singleton.hpp> | |
#include "Object/ServerPlayer.h" | |
#include "GameInterface/Observer/Subject.h" | |
namespace server { | |
class PlayerManager public boost::noncopyable, public boost::serialization::singleton<PlayerManager> { | |
public: | |
friend class boost::serialization::singleton<PlayerManager>; | |
static PlayerManager &getInstance() { | |
return boost::serialization::singleton<PlayerManager>::get_mutable_instance(); | |
} | |
private: | |
}; | |
} | |
#endif //SDL2_TETRIS_SERVER_PLAYERMANAGER_H |
이와같이 구현하면 무난하게 싱글턴을 구현해낼 수 있습니다.
thread-safe를 위한 방법은 lock, unlock으로 해결하고 있습니다.
https://www.boost.org/doc/libs/1_39_0/libs/serialization/doc/singleton.html#multithreading
singleton 클래스를 따라가보면 재밌게도 템플릿을 이용하여 싱글턴할 객체를 상속하여
이용하고 있다는 점 입니다.
boost의 singleton 클래스를 보면 쉽게 알 수 있지만,
static 변수를 이용하면 단점으로는 어느 시점에 객체가 생성되는지 불분명 하다는 점입니다.
(boost를 사용하지 않아도 쉽게 사용할 수 있는 방법으로 많이 쓰일것 입니다.)
힙이나 스택에 생성되는것이 아닌 전역공간에 할당되기에 이는 컴파일러에 따라 각기 다를것입니다.
심지어 사용하지도 않을 객체가 생성되는 문제가 있습니다.
이러한 문제를 보완하기 위한 전략은 추후의 글을 통해 논하고자 합니다.
'프로그래밍 > C C++' 카테고리의 다른 글
The story behind printf 2편 (0) | 2019.01.27 |
---|---|
The story behind printf 1편 (0) | 2019.01.22 |
gcc와 msvc에서 range-based for loop(범위 기반 반복문)사용의 주의점. (0) | 2018.05.22 |
Item20 : Specify comparsion types for associative conatainers of poniters (0) | 2018.05.13 |
Item 19: Understand the difference between equality and equivalence (0) | 2018.04.17 |
- Total
- Today
- Yesterday
- 피아노
- 문자열
- yiruma
- 중국
- regex
- peram jam
- cpp
- Codejam
- link
- Pointer
- 카카오 공채
- Spring
- kernerl
- 코드잼
- 중국여행
- Algorithm
- compile
- 정규표현식
- STL
- 사천
- linux
- C language
- printf
- 여행
- 알고리즘
- C++
- 드럼
- 이루마
- 악보
- python
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |