静态对象的私有析构函数是如何调用的

How are the private destructors of static objects called?

本文关键字:何调用 调用 对象 析构函数 静态      更新时间:2023-10-16

可能重复:
无法访问singleton类析构函数中的私有成员

我正在实现一个singleton,如下所示。

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

析构函数是私有的。当程序即将终止时,会为MainInstance对象调用此函数吗?

我在Visual studio 6中尝试过,但它出现了编译错误。

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

在visualstudio2010中,它被编译,并且析构函数被称为

根据标准,这里应该有什么期望?

编辑:由于VisualStudio6的行为并没有那么愚蠢,所以出现了混乱。可以说,静态对象的A的构造函数是在A的函数的上下文中调用的。但析构函数不是在同一函数的上下文中调用的。这是从全球背景下调用的。

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的析构函数在声明时是可访问的,因此您的示例应该没有错误。