How are the private destructors of static objects called? [duplicate]

拈花ヽ惹草 提交于 2019-12-01 00:59:06

问题


Possible Duplicate:
Cannot access private member in singleton class destructor

I'm implementing a singleton as below.

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;
 }

The destructor is private. Will this get called for the object theMainInstance when the program is about to terminate?

I tried this in Visual studio 6, it gave a compilation error.

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

In visual studio 2010, this got compiled and the destructor was called.

What should be the expectation here according to the standard?

Edit : The confusion arises since Visual Studio 6 behaviour is not so dumb. It can be argued that the constructor of A for the static object is called in the context of a function of A. But the destructor is not called in the context of the same function. This is called from a global context.


回答1:


Section 3.6.3.2 of the C++03 standard says:

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.

It doesn't give any restriction regarding having a private destructor, so basically if it gets created it will also get destroyed.

A private destructor does cause a restriction on the ability to declare an object (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

but since the destructor of A::theMainInstance is accessible at the point of declaration, your example should have no error.



来源:https://stackoverflow.com/questions/11524131/how-are-the-private-destructors-of-static-objects-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!