c++ - 当结构具有默认构造函数时,为什么我的 C++ 程序在 Release模式下崩溃?

标签 c++ crash

环境: - GNU/Linux(Ubuntu 14.04 和 Mageia 5) - GCC 4.9.2(在 Mageia 下) - 系统Qt5和提升

直到最近,我的程序在调试和 Release模式下都没有问题。不相关的更改(并且没有很好地识别)使它崩溃,但仅在 Release模式下。不在调试中。

在调试中,valgrind 不会发出任何错误信号。在发布中,它报告使用了未初始化的数据,但在方法的开头。通过系统搜索,我能够追踪到以下结构的使用:

struct LIMA_LINGUISTICANALYSISSTRUCTURE_EXPORT LinguisticElement {
  StringsPoolIndex inflectedForm;
  StringsPoolIndex lemma;
  StringsPoolIndex normalizedForm;
  LinguisticCode properties;
  MorphoSyntacticType type;
  bool operator==(const LinguisticElement& le) const;
  bool operator<(const LinguisticElement& le) const;
};

StringsPoolIndex 和 LinguisticCode 定义为:

BOOST_STRONG_TYPEDEF(uint64_t, StringsPoolIndex);
BOOST_STRONG_TYPEDEF(uint32_t, LinguisticCode);

并且 MorphoSyntacticType 是一个枚举。

如果我添加显式构造函数和一个 operator=,崩溃就会消失并且 valgrind 会停止发出错误信号。

LinguisticElement::LinguisticElement() :
  inflectedForm(0),
  lemma(0),
  normalizedForm(0),
  properties(0),
  type(NO_MORPHOSYNTACTICTYPE)

{
}
LinguisticElement::LinguisticElement(const  LinguisticElement& le) :
  inflectedForm(le.inflectedForm),
  lemma(le.lemma),
  normalizedForm(le.normalizedForm),
  properties(le.properties),
  type(le.type)
{
}
LinguisticElement& LinguisticElement::operator=(const LinguisticElement& le)
{
  inflectedForm = le.inflectedForm;
  lemma = le.lemma;
  normalizedForm = le.normalizedForm;
  properties = le.properties;
  type = le.type;
  return *this;
}

我不明白为什么会发生这种情况,因为我的实现与编译器生成的实现相同,如果我理解得很好的话。还是我错了?

最佳答案

您已将 StringsPoolIndexLinguisticCode 定义为固定宽度的整数类型。因此,它们不会由您的结构的编译器合成构造函数初始化。变量通常在 Debug模式下初始化为 null(或某些很少发生的特定值),而除非明确说明,否则在 Release模式下不会发生同样的情况。这就是您仅在发布构建配置中遇到崩溃的原因。

关于c++ - 当结构具有默认构造函数时,为什么我的 C++ 程序在 Release模式下崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34199706/

相关文章:

c - 字符串数组上的基本 qsort 在 qsort() 中崩溃

c++ - 如何在运算符重载中解释 "operator const char*()"?

c++ - 什么是关于句柄的不透明标识符?

c++ - 删除悬挂指针时会发生什么?

c++ - 如何初始化这个填充有&functionA, &functionB 的数组?

c++ - unsigned char (*pArray[10][10])的含义;

crash - 如何解决 malloc 崩溃问题

javascript - 粘贴以下代码后,我的浏览器崩溃了。为什么?

golang log.Printf 崩溃

c - 程序因函数原型(prototype)声明而崩溃