이건 싱글턴 클래스
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 | template < typename T > class singleton { public: template < typename ...Args > static void create(Args... args) { unique_instance = std::make_unique<T>(args...); } static T& get_instance() { return *unique_instance; } static void destory() { unique_instance.reset(); } private: static std::unique_ptr<T> unique_instance; }; template < typename T > std::unique_ptr<T> singleton<T>::unique_instance = nullptr; | cs |
전에 써주신 코드를 기반으로 함수를 만들어 봤는데.
create를 그대로 쓰면 매개변수인 Args들은 항상 복사 생성되서 make_unique<T>(args...)로 전달되는거죠?
문제가 생긴게 이 함수에 좌측값 참조를 전달했는데 복사해버리더라구요
그래서
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 | template < typename T > class singleton { public: template < typename ...Args > static void create(Args&&... args) { unique_instance = std::make_unique<T>(std::forward<Args>(args)...); } static T& get_instance() { return *unique_instance; } static void destory() { unique_instance.reset(); } private: static std::unique_ptr<T> unique_instance; }; template < typename T > std::unique_ptr<T> singleton<T>::unique_instance = nullptr; | cs |
이렇게 고치면 잘 작동하던데
이렇게 하면 되는건가요?
보편참조니 완벽전달이니 이제야 좀 이해가 가는 거 같은데...
댓글 0