static: クラス共有メンバ
インスタンスを作らずにアクセス。カウンタやシングルトンに。
static
クラス全体で共有されるメンバ。
inline static
C++17。ヘッダ内で初期化可能。
シングルトン
インスタンスが1つだけのパターン。
static メンバ
staticメンバはオブジェクト(インスタンス)に紐付かず、クラスそのものに紐付きます。インスタンスを1つも作らなくても `Counter::getCount()` のように呼び出せます。グローバル変数に似ていますが、クラスの中に閉じ込められているため、名前の衝突を防げます。
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 (C++17) で定数定義class Config {public: inline static std::string version = "1.0.0"; inline static const int maxConnections = 100;};
// constexpr staticclass 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 で実装してください。