본문 바로가기

Win32 api

Win32 api 강의 7화.

- Singleton 패턴 설명.

#pragma once
// 싱글톤 패턴
// 객체의 생성을 1개로 제한하는 대신, 어디서든 접근 가능.
class CCore
{
public:
    static CCore* GetInst()
    {
        static CCore* pCore = nullptr;

        // 최초 호출.
        if (pCore == nullptr)
        {
            pCore = new CCore;
        }

        return pCore;
    }

    static void ReleaseInst()
    {
        CCore* pCore = GetInst();
        delete pCore;
    }
private:
    CCore() {}
    ~CCore() {}
};

싱글톤 객체를 static 멤버 함수 안에 선언. 이렇게 하면 ReleaseInst 함수에서 delete 해도

GetInst 함수 내에 선언된 static 변수는 사라지지 않음. 따라서 

    CCore::GetInst();
    CCore::ReleaseInst();

    CCore::GetInst();
    CCore::ReleaseInst();

이렇게 호출했을 때 dangling pointer 문제가 발생함.

 

두 함수에서 선언된 pCore 가 다르기 때문에 벌어진 일이다. 따라서 하나로 묶어야 함.

 

public:
    static CCore* GetInst()
    {
        if (g_pInst == nullptr)
        {
            g_pInst = new CCore;
        }

        return g_pInst;
    }
    static void ReleaseInst()
    {
        if (g_pInst)
        {
            delete g_pInst;
            g_pInst = nullptr;
        }
    }

private:
    static CCore* g_pInst;

수정된 코드. g_pInst 라는 하나의 static 멤버 변수로 싱글톤 객체를 관리하였다.

 

'Win32 api' 카테고리의 다른 글

Win32 api 강의 9화.  (0) 2025.09.12
Win32 api 강의 8화.  (0) 2025.09.12
Win32 api 강의 6화.  (0) 2025.09.11
Win32 api 강의 5화.  (0) 2025.09.11
Win32 api 강의 4화.  (0) 2025.09.10