What are private static object destructors called?

Possible duplicate:
Unable to access private member in singleton class destructor

I implement singleton as shown 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 it be called for theMainInstance when the program is about to exit?

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

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

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

What should be the expectation here according to the standard?

Edit: Confusion occurs because the behavior of Visual Studio 6 is not so stupid. It can be argued that constructor A for a static object is called in the context of function A. But the destructor is not called in the context of the same function . This is called from a global context.

+6
source share
1 answer

Section 3.6.3.2 of the C ++ 03 standard states:

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 does not give any restrictions regarding the presence of a private destructor, so basically, if it is created, it will also be destroyed.

A private destructor causes 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 A :: theMainInstance is available at the declaration point, your example should not have an error.

+4
source

Source: https://habr.com/ru/post/920687/


All Articles