コーディングについて学ぶにつれて、さまざまなことを試してみるのが好きです。実行時に構造体の単一のインスタンスのみを必要とするプログラムがあり、シングルトン構造体を作成できるかどうか疑問に思っていました。シングルトン クラスの作成に関する情報はインターネット上にたくさんありますが、シングルトン構造体の作成に関する情報はありません。これはできますか?もしそうなら、どのように?
前もって感謝します。ああ、私はC++で働いています。
Aclass
と astruct
は、細かい点 (メンバーの既定のアクセス レベルなど) を除いて、ほとんど同じものです。たとえば、次のようになります。
struct singleton
{
static singleton& get_instance()
{
static singleton instance;
return instance;
}
// The copy constructor is deleted, to prevent client code from creating new
// instances of this class by copying the instance returned by get_instance()
singleton(singleton const&) = delete;
// The move constructor is deleted, to prevent client code from moving from
// the object returned by get_instance(), which could result in other clients
// retrieving a reference to an object with unspecified state.
singleton(singleton&&) = delete;
private:
// Default-constructor is private, to prevent client code from creating new
// instances of this class. The only instance shall be retrieved through the
// get_instance() function.
singleton() { }
};
int main()
{
singleton& s = singleton::get_instance();
}
構造体とクラスは、C++ ではほとんど同じです (唯一の違いは、メンバーのデフォルトの可視性です)。
シングルトンを作成する場合は、構造体/クラスのユーザーがインスタンス化できないようにする必要があるため、ctor と copy-ctor を非表示にすることは避けられないことに注意してください。
struct Singleton
{
private:
static Singleton * instance;
Singleton()
{
}
Singleton(const Singleton & source)
{
// Disabling copy-ctor
}
Singleton(Singleton && source)
{
// Disabling move-ctor
}
public:
Singleton * GetInstance()
{
if (instance == nullptr)
instance = new Singleton();
return instance;
}
}
概念的には、C++ ではastruct
と aは同じであるため、 singletonを作成することは singleton を作成することと同じです。class
struct
class
class
との唯一の違いstruct
は、デフォルトのアクセス指定子と基本クラスの継承です: private
forclass
とpublic
for struct
. 例えば、
class Foo : public Bar
{
public:
int a;
};
と同じです
struct Foo : Bar
{
int a;
};
したがって、シングルトンに関しては基本的な違いはありません。シングルトンが悪いと見なされる理由を必ず読んでください。
簡単な実装を次に示します。
struct singleton
{
static singleton& instance()
{
static singleton instance_;
return instance_;
}
singleton(const singleton&)=delete; // no copy
singleton& operator=(const singleton&)=delete; // no assignment
private:
singleton() { .... } // constructor(s)
};
まずstruct
、class
メンバーのデフォルトのアクセスのみを参照してください。クラスでできることはすべて、構造体で行うことができます。POD 構造体を参照していた場合、事態はさらに複雑になります。カスタム コンストラクターを定義することはできないため、単一のオブジェクトの作成のみを強制する方法はありません。ただし、単純に 1 回だけインスタンス化することを妨げるものは何もありません。
class
C++ ではほぼ同義語struct
です。シングルトンのユースケースでは、それらは完全な同義語です。