C ++静态const变量和销毁 [英] C++ static const variable and destruction

查看:175
本文介绍了C ++静态const变量和销毁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用简单的C ++类时遇到了奇怪的行为。

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

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?

谢谢,
Norbert

thanks, Norbert

推荐答案


我希望访问冲突或类似的
,但我从不希望
包含静态const $ b的内容$ b字符串可能会更改。

I'd expect access violations or anything similar, but I'd never expect that the content of the static const string could change.

未定义的行为:它是未定义的。如果CONST_STR已被销毁,则不能保证在访问它时发生硬件异常。它可能会崩溃,但其地址可能最终再次包含看起来像一个空字符串的数据:其析构函数可能会清除指针或其他内容。

Undefined behaviour: it is undefined. If CONST_STR has been destroyed, then you are not guaranteed a hardware exception if you access it. It might crash, but then again its address might end up containing data which looks like an empty string: its destructor might clear pointers or whatever.

在这种情况下,您说A实例也存储在全局智能指针中,该指针在main()中分配。因此,在A构造函数中访问时已构造CONST_STR,但很可能在销毁智能指针之前将其销毁。我们需要整个程序都可以肯定地说。

In this case, you say that the A instance is also stored in a global smart pointer, which is assigned in main(). So the CONST_STR has been constructed when it is accessed in the A constructor, but quite possibly is destroyed before the smart pointer is destroyed. We'd need the whole program to say for sure.

这篇关于C ++静态const变量和销毁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆