Per*_*est 8 c++ standards static destructor
可能重复:
无法访问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;
}
Run Code Online (Sandbox Code Playgroud)
该析构函数是私有的.当程序即将终止时,是否会调用对象theMainInstance?
我在Visual Studio 6中尝试了这个,它给出了编译错误.
"cannot access private member declared in class..."
Run Code Online (Sandbox Code Playgroud)
在visual studio 2010中,这被编译并且析构函数被调用.
根据标准,这里应该有什么期望?
编辑:由于Visual Studio 6的行为不那么愚蠢,因此出现了混乱.可以说,静态对象的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 的析构函数在声明时可以访问,因此您的示例应该没有错误。