可能的重复:
无法访问单例类析构函数中的私有成员
我正在实现一个单例,如下所示。
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 析构函数是私有的。当程序即将终止时,是否会为对象 theMainInstance 调用此函数?
我在 Visual Studio 6 中尝试了这个,它给出了编译错误。
"cannot access private member declared in class..."
在 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 的析构函数在声明时可以访问,因此您的示例应该没有错误。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)