객체를 한 개만 생성하는 방법

클래스의 정적 멤버로 선언된 객체는 그것이 사용되든 사용되지 않든 상관없이 생성됨

함수 안에서 정적 변수로 선언된 객체는 함수가 최소한 한 번 호출되어야 생성됨

 

클래스의 정적 멤버로 선언된 객체는 초기화 시점이 정확하게 정의되어 있지 않음

  • C++는 하나의 컴파일 단위(오브젝트 파일) 안에 선언된 정적 객체들의 초기화 순서는 보장하고 있지만 서로 다른 컴파일 단위에 있는 정적 객체의 초기화 순서는 정의하지 않음

함수 안에서 정적 변수로 선언된 객체는 초기화 시점이 함수가 처음 호출되는 시점으로 명확함

 

정적 객체를 선언한 비멤버 함수를 inline으로 선언하면 호출하는 곳마다 정적 객체가 선언되므로 inline으로 선언하면 안됨

Printer& thePrinter()
{
    static Printer p;
    return p;
}

 

인스턴스 카운팅 기능을 가진 기본 클래스

template <class BeingCounted>
class Counted
{
public:
    class TooManyObjects
    {};

    static size_t objectCount() { return numObjects; }

protected:
    Counted();
    Counted(const Counted&);
    virtual ~Counted() { --numObjects; }

private:
    void init();

    static size_t numObjects;
    static const size_t maxObjects;
};

template <class BeingCounted>
Counted<BeingCounted>::Counted()
{
    init();
}

template <class BeingCounted>
Counted<BeingCounted>::Counted(const Counted<BeingCounted>&)
{
    init();
}

template <class BeingCounted>
void Counted<BeingCounted>::init()
{
    if (numObjects >= maxObjects)
    {
        throw TooManyObjects();
    }

    ++numObjects;
}

각 클래스마다 별도의 카운터를 두어야하기 때문에 클래스 템플릿으로 구현

기본 클래스로만 사용되도록 설계됐기 때문에 생성자와 소멸자가 모두 protected로 선언됨

예외 대신에 다른 알림으로도 사용할 수 있음

+ Recent posts

목차