static: クラス共有メンバ

インスタンスを作らずにアクセス。カウンタやシングルトンに。

static
クラス全体で共有されるメンバ。
inline static
C++17。ヘッダ内で初期化可能。
シングルトン
インスタンスが1つだけのパターン。

static メンバ

教室の黒板 (Shared Whiteboard)

通常のメンバ変数は「個人のノート」です。学生(インスタンス)ごとに別々の内容を書けます。一方、staticメンバは「教室の黒板」です。クラスにつき1つしか存在せず、全員(全インスタンス)が同じ黒板を見て、共有します。

staticメンバはオブジェクト(インスタンス)に紐付かず、クラスそのものに紐付きます。インスタンスを1つも作らなくても `Counter::getCount()` のように呼び出せます。グローバル変数に似ていますが、クラスの中に閉じ込められているため、名前の衝突を防げます。

Static Members
class Counter {
static int count_; // クラスで共有される変数
public:
Counter() { ++count_; }
~Counter() { --count_; }
static int getCount() { // static メソッド
// this ポインタは使えない
return count_;
}
};
// static メンバ変数の実体定義(C++17以前は必須)
int Counter::count_ = 0;
int main() {
Counter a, b, c;
// インスタンスがなくても呼べる
std::cout << Counter::getCount(); // 3
}
実行結果
Counter a, b, c;\nCounter::getCount() → 3
Bad
// ❌ Bad: グローバル変数
int g_counter = 0;
void increment() { g_counter++; }
// どこからでも変更できて危険、名前衝突のリスク
Good
// ✅ Good: static メンバ
class Counter {
// C++17: inline static でヘッダだけで初期化完結
inline static int count_ = 0;
public:
static void increment() { count_++; }
};

パターン

inline static, Singleton
// inline static (C++17) で定数定義
class Config {
public:
inline static std::string version = "1.0.0";
inline static const int maxConnections = 100;
};
// constexpr static
class Math {
static constexpr double PI = 3.14159265359;
};
// シングルトンパターン(Meyers Singleton)
class Singleton {
// コンストラクタを private に
Singleton() = default;
public:
static Singleton& instance() {
// 関数内の static 変数は初回呼び出し時に一度だけ初期化される
// スレッドセーフ(C++11以降)
static Singleton s;
return s;
}
// コピー禁止
Singleton(const Singleton&) = delete;
void operator=(const Singleton&) = delete;
};
Tip: C++17 なら inline static を使うことで、cppファイルでの定義が不要になります。

合格ライン

static メンバの定義と初期化ができる
シングルトンパターンを実装できる

参考リンク

演習課題

課題1: static カウンタ
オブジェクト数をカウントする static メンバを作成してください。
課題2: シングルトン
シングルトンパターンを static で実装してください。

次のステップ