C++ static 멤버 | "Static Members" 가이드

C++ static 멤버 | "Static Members" 가이드

이 글의 핵심

C++ static 멤버에 대해 정리한 개발 블로그 글입니다. class Counter { private: static int count;

static 멤버 변수

모든 객체가 공유하는 클래스 레벨 변수

class Counter {
private:
    static int count;  // 선언
    
public:
    Counter() {
        count++;
    }
    
    ~Counter() {
        count--;
    }
    
    static int getCount() {
        return count;
    }
};

// 정의 (클래스 외부)
int Counter::count = 0;

int main() {
    cout << Counter::getCount() << endl;  // 0
    
    Counter c1;
    cout << Counter::getCount() << endl;  // 1
    
    Counter c2;
    cout << Counter::getCount() << endl;  // 2
    
    {
        Counter c3;
        cout << Counter::getCount() << endl;  // 3
    }
    
    cout << Counter::getCount() << endl;  // 2
}

static 멤버 함수

객체 없이 호출 가능한 함수

class Math {
public:
    static int add(int a, int b) {
        return a + b;
    }
    
    static int multiply(int a, int b) {
        return a * b;
    }
};

int main() {
    // 객체 없이 호출
    cout << Math::add(3, 4) << endl;       // 7
    cout << Math::multiply(3, 4) << endl;  // 12
}

static vs non-static

class Example {
private:
    int instanceVar;
    static int staticVar;
    
public:
    Example(int val) : instanceVar(val) {}
    
    // non-static 멤버 함수
    void instanceFunc() {
        instanceVar++;  // OK
        staticVar++;    // OK
    }
    
    // static 멤버 함수
    static void staticFunc() {
        // instanceVar++;  // 에러: this 없음
        staticVar++;       // OK
    }
};

int Example::staticVar = 0;

실전 예시

예시 1: 싱글톤

class Database {
private:
    static Database* instance;
    
    // private 생성자
    Database() {
        cout << "Database 연결" << endl;
    }
    
public:
    // 복사/이동 금지
    Database(const Database&) = delete;
    Database& operator=(const Database&) = delete;
    
    static Database* getInstance() {
        if (instance == nullptr) {
            instance = new Database();
        }
        return instance;
    }
    
    void query(const string& sql) {
        cout << "쿼리 실행: " << sql << endl;
    }
};

Database* Database::instance = nullptr;

int main() {
    Database* db1 = Database::getInstance();
    Database* db2 = Database::getInstance();
    
    cout << (db1 == db2) << endl;  // 1 (같은 인스턴스)
    
    db1->query("SELECT * FROM users");
}

예시 2: 객체 카운터

class Widget {
private:
    static int totalCount;
    static int activeCount;
    int id;
    
public:
    Widget() : id(++totalCount) {
        activeCount++;
        cout << "Widget " << id << " 생성" << endl;
    }
    
    ~Widget() {
        activeCount--;
        cout << "Widget " << id << " 소멸" << endl;
    }
    
    static int getTotalCount() {
        return totalCount;
    }
    
    static int getActiveCount() {
        return activeCount;
    }
};

int Widget::totalCount = 0;
int Widget::activeCount = 0;

int main() {
    cout << "총 생성: " << Widget::getTotalCount() << endl;  // 0
    cout << "활성: " << Widget::getActiveCount() << endl;    // 0
    
    Widget w1;
    cout << "총 생성: " << Widget::getTotalCount() << endl;  // 1
    cout << "활성: " << Widget::getActiveCount() << endl;    // 1
    
    {
        Widget w2, w3;
        cout << "총 생성: " << Widget::getTotalCount() << endl;  // 3
        cout << "활성: " << Widget::getActiveCount() << endl;    // 3
    }
    
    cout << "활성: " << Widget::getActiveCount() << endl;  // 1
}

예시 3: 설정 관리자

class Config {
private:
    static map<string, string> settings;
    
public:
    static void set(const string& key, const string& value) {
        settings[key] = value;
    }
    
    static string get(const string& key, const string& defaultValue = "") {
        auto it = settings.find(key);
        return it != settings.end() ? it->second : defaultValue;
    }
    
    static bool has(const string& key) {
        return settings.find(key) != settings.end();
    }
    
    static void printAll() {
        for (const auto& [key, value] : settings) {
            cout << key << " = " << value << endl;
        }
    }
};

map<string, string> Config::settings;

int main() {
    Config::set("host", "localhost");
    Config::set("port", "8080");
    Config::set("debug", "true");
    
    cout << "Host: " << Config::get("host") << endl;
    cout << "Port: " << Config::get("port") << endl;
    
    Config::printAll();
}

예시 4: 팩토리

class Shape {
public:
    virtual void draw() const = 0;
    virtual ~Shape() = default;
};

class Circle : public Shape {
public:
    void draw() const override {
        cout << "Circle" << endl;
    }
};

class Rectangle : public Shape {
public:
    void draw() const override {
        cout << "Rectangle" << endl;
    }
};

class ShapeFactory {
public:
    static unique_ptr<Shape> create(const string& type) {
        if (type == "circle") {
            return make_unique<Circle>();
        } else if (type == "rectangle") {
            return make_unique<Rectangle>();
        }
        return nullptr;
    }
};

int main() {
    auto shape1 = ShapeFactory::create("circle");
    auto shape2 = ShapeFactory::create("rectangle");
    
    shape1->draw();  // Circle
    shape2->draw();  // Rectangle
}

static const

class Constants {
public:
    static const int MAX_SIZE = 100;
    static const double PI;
};

const double Constants::PI = 3.14159;

int main() {
    cout << Constants::MAX_SIZE << endl;  // 100
    cout << Constants::PI << endl;        // 3.14159
}

inline static (C++17)

class Config {
public:
    // C++17: inline static (외부 정의 불필요)
    inline static int maxConnections = 100;
    inline static string serverName = "localhost";
};

int main() {
    cout << Config::maxConnections << endl;  // 100
    cout << Config::serverName << endl;      // localhost
}

자주 발생하는 문제

문제 1: 초기화 순서

// ❌ 초기화 순서 불확실
class A {
public:
    static int value;
};

class B {
public:
    static int value;
};

int A::value = B::value + 1;  // B::value가 초기화 안됐을 수 있음
int B::value = 10;

// ✅ 함수 내 static
class A {
public:
    static int& getValue() {
        static int value = B::getValue() + 1;
        return value;
    }
};

class B {
public:
    static int& getValue() {
        static int value = 10;
        return value;
    }
};

문제 2: 스레드 안전성

// ❌ 스레드 안전하지 않음
class Counter {
private:
    static int count;
    
public:
    static void increment() {
        count++;  // 경쟁 조건
    }
};

// ✅ mutex 사용
class Counter {
private:
    static int count;
    static mutex mtx;
    
public:
    static void increment() {
        lock_guard<mutex> lock(mtx);
        count++;
    }
};

int Counter::count = 0;
mutex Counter::mtx;

문제 3: 정의 누락

// ❌ 정의 누락
class Example {
public:
    static int value;  // 선언만
};

// int Example::value = 0;  // 정의 누락 (링크 에러)

// ✅ 정의 추가
class Example {
public:
    static int value;
};

int Example::value = 0;  // 정의

FAQ

Q1: static 멤버는 언제 사용?

A:

  • 모든 객체가 공유할 데이터
  • 유틸리티 함수
  • 싱글톤 패턴

Q2: static 함수에서 this?

A: 불가. this는 객체 포인터.

Q3: static 멤버 초기화는?

A: 클래스 외부에서 정의. C++17은 inline static 가능.

Q4: static vs 전역 변수?

A: static은 클래스 스코프. 캡슐화 유지.

Q5: 스레드 안전?

A: 아니요. mutex 등으로 보호 필요.

Q6: static 멤버 학습 리소스는?

A:

  • “Effective C++”
  • cppreference.com
  • “C++ Primer”

같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.

  • C++ this Pointer | “this 포인터” 가이드
  • C++ Initialization Order 완벽 가이드 | 초기화 순서의 모든 것
  • C++ Linkage와 Storage | “연결과 저장 기간” 가이드

관련 글

  • C++ Initialization Order 완벽 가이드 | 초기화 순서의 모든 것
  • C++ this Pointer |
  • C++ 클래스와 객체 |
  • C++ struct vs class |
  • C++ CRTP 완벽 가이드 | 정적 다형성과 컴파일 타임 최적화