8

重複の可能性:
シングルトン クラスのデストラクタでプライベート メンバーにアクセスできない

以下のようにシングルトンを実装しています。

class A
{
public:

    static A& instance();
private:
    A(void)
    {
        cout << "In the constructor" << endl;
    }
    ~A(void)
    {
        cout << "In the destructor" << endl;
    }

};

A& A::instance()
{
    static A theMainInstance;
    return theMainInstance;
}

int main()
{
    A& a = A::instance();

    return 0;
 }

デストラクタは privateです。プログラムが終了しようとしているときに、これはオブジェクト theMainInstance に対して呼び出されますか?

これを Visual Studio 6 で試したところ、コンパイル エラーが発生しました。

"cannot access private member declared in class..."

Visual Studio 2010 では、これがコンパイルされ、デストラクタが呼び出されました。

標準によると、ここで何を期待する必要がありますか?

編集:Visual Studio 6の動作はそれほど馬鹿げていないため、混乱が生じます。静的オブジェクトの A のコンストラクターは、A の関数のコンテキストで呼び出されると主張できます。しかし、デストラクタは、同じ関数のコンテキストで呼び出されません。これは、グローバル コンテキストから呼び出されます。

4

1 に答える 1

4

C++03 標準のセクション 3.6.3.2 には次のように記載されています。

Destructors for initialized objects of static storage duration (declared at block scope or at namespace scope) are called as a result of returning from main and as a result of calling exit.

プライベートデストラクタを持つことに関して制限を与えないため、基本的に作成された場合も破棄されます。

プライベート デストラクタにより、オブジェクトを宣言する機能が制限されます (C++03 12.4.10)

A program is ill-formed if an object of class type or array thereof is declared and the destructor for the class is not accessible at the point of declaration

ただし、 A::theMainInstance のデストラクタは宣言の時点でアクセスできるため、この例ではエラーは発生しません。

于 2012-07-17T14:20:01.043 に答える