FIX: Destructor of Static Object Not Called on Exit (236114)



The information in this article applies to:

  • Microsoft Visual C++, 32-bit Enterprise Edition 5.0
  • Microsoft Visual C++, 32-bit Enterprise Edition 6.0
  • Microsoft Visual C++, 32-bit Professional Edition 5.0
  • Microsoft Visual C++, 32-bit Professional Edition 6.0
  • Microsoft Visual C++, 32-bit Learning Edition 6.0

This article was previously published under Q236114

SYMPTOMS

The destructor for static local variables in static objects may never be called. The destructor should be called when the program exits, but it does not get called. See the More Information section below for a specific example.

RESOLUTION

Avoid using this construct.

STATUS

Microsoft has confirmed that this is a bug in the Microsoft products that are listed at the beginning of this article.

This problem was corrected in Microsoft Visual C++ .NET.

MORE INFORMATION

The static local won't be destroyed if it is local to a destructor for which the only instance(s) of the destructor's class is static. If there are any local or heap allocated instances, the object will be destroyed (assuming delete is called for heap allocated instances).

The following code demonstrates the problem:
#include <iostream>

struct X {
	X() {std::cout << "constructor X" << std::endl;} 
	~X() {std::cout << "destructor X" << std::endl;} // destructor of X is never called.
};

struct Y {
   ~Y() {static X x;}
};

void main() {
   static Y y;
}
				

Modification Type:MajorLast Reviewed:12/11/2003
Keywords:kbBug kbCompiler kbCPPonly kbfix kbNoUpdate KB236114