静态对象的私有析构函数是如何调用的
How are the private destructors of static objects called?
可能重复:
无法访问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的析构函数在声明时是可访问的,因此您的示例应该没有错误。
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 函数调用中参数的顺序重要吗
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 函数何时会在c++中包含stack_Unwind_Resume调用
- Singleton模式中的手动析构函数调用:调用多次
- 从同一父调用调用不同的子类函数
- 我可以通过CPP程序中的数据库调用调用Java程序
- C++17标准对在nullptr上调用delete有何规定
- NSIS系统::调用-调用方法失败
- 参数构造函数调用调用
- 当 int 方法工作正常时,void 方法有何不同,或者为什么我不能调用 void 方法?
- 让非托管 C++ 代码调用调用 C# 代码的托管 C++ 代码
- 关于在矢量上调用clear如何改变容量,标准有何规定
- 如何让函数调用调用它的函数
- 如何p/调用调用函数只使用,但c++需要.a/.lib/.o文件
- C#DLL可以调用调用本机C++静态库的C++/CLI托管包装器吗