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

Why my C++ program crash in release mode when a struct has default constructors?

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

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

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