[C++] Singleton Pattern

jh Seo·2023년 5월 31일
0

C++공부

목록 보기
17/21

개요

c++과 ncurses를 이용해 뱀게임을 구현하던중
충돌 처리하는 매니저가 싱글턴패턴이면 편리하게 호출할거같아서
공부했다.

여러문서를 참조했고 제일 추천하는 방식은 밑의 방식이다.

#include <iostream>

class Singleton {
private:
    Singleton() {}
    Singleton(const Singleton& other) {}
    Singleton& operator=(const Singleton& other) {}
    ~Singleton() {}
public:
    static Singleton& GetInstance() {
        static Singleton s;
        return s;
    }
};

int main(void) {
    Singleton& s = Singleton::getInstance();
    return 0;
}

이런식으로 GetInstance()를 호출할때 static으로 선언된 싱글톤 클래스를 반환하는 방식이였다.
이런식으로 구현하면 GetInstance함수를 호출하지 않으면 객체의 생성도 되지 않아서 효율적이다.

static Singleton& GetInstance 부분을

 static Singleton* GetInstance()
    {
        static Singleton ins;
        return &ins;
    }

이런식으로 포인터를 넘기는 방식도 있다.

생각

포인터를 넘기는 방법이 개인적으로 더 편해보인다.
참조자를 넘기게 되면 참조자가 받아야하는데, 참조자는 생성과 동시에 할당해줘야하므로
클래스의 멤버변수로 참조자를 적게되거나하면 참조자적고 바로 GetInstance를 호출해야하기 때문이다,

레퍼런스

https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=neos_rtos&logNo=220738606946

https://hwan-shell.tistory.com/227

profile
코딩 창고!

0개의 댓글