C++ static const variable and destruction

2019-08-15 12:12发布

I have encountered a strange behavior with a simple C++ class.

classA.h

class A
{
public:
  A();
  ~A();
  static const std::string CONST_STR;
};

classA.cpp

#include "classA.h"
#include <cassert>

const std::string A::CONST_STR("some text");

A::A()
{
  assert(!CONST_STR.empty()); //OK
}

A::~A()
{
  assert(!CONST_STR.empty()); //fails
}

main.cpp

#include <memory>  
#include <classA.h>  

std::auto_ptr<A> g_aStuff; 

int main() 
{ 
  //do something ... 
  g_aStuff = std::auto_ptr<A>(new A()); 
  //do something ... 
  return 0; 
}

I'd expect access violations or anything similar, but I'd never expect that the content of the static const string could change. Does anyone here have a good explanation what happens in that code?

thanks, Norbert

7条回答
做个烂人
2楼-- · 2019-08-15 13:01

It might happen if there is a global instance of A (or a static class member of type A). Since the order of the initialization of globals and statics is not defined (cross translation units), it can be.

查看更多
登录 后发表回答