C ++中的结构未初始化问题

struct uninitialization issue in c++

我有以下三个结构定义,对于 SA, SBad, SC,我简化了名称和成员来演示问题。

 struct SA {
     int snap;
 };

 template <int W> class VString
 {
     char data[W];
   public:
     VString() { }
 };

 struct SBad {
     VString<9> s;
     int i;
 };

 struct SC {
     int inst;
 };

我有一个包含结构来保存来自由上述结构组成的网络的数据:

 struct S {
     std::vector<SA>           m_a;
     SBad                      m_bad;
     std::vector<SC>           m_c;
 };

并且在代码中我需要经常重置结构,其中:

// data member
S m_s;
// member function
void clear() {
   m_s.m_bad   = {};
}

我使用的是 gcc 7.3.1 版。对于调试版本,这工作正常,对于发布版本,它失败了:

error: '<anonymous>' is used uninitialized in this function [-Werror=uninitialized]

gcc 标志是:

-std=c++11 -O3 -Werror -Wall

为什么会出现这个错误,这是一种将数据初始化为零的定义方式,对吧? 如果我改为:

void clear() {
    SA sa{};
    m_s.a = sa;
    m_s.b = {};
    ...
}

相反,发布构建将会成功。

更新:

我创建了一个 minimum working test case 来显示这个问题。

您只能对“聚合”使用 curly-brace 初始化。引用标准:

An aggregate is an array or a class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10), and no virtual functions (10.3).

...

When an aggregate is initialized the initializer can contain an initializer-clause consisting of a brace-enclosed, comma-separated list of initializer-clauses for the members of the aggregate, written in increasing subscript or member order. If the aggregate contains subaggregates, this rule applies recursively to the members of the subaggregate.

在您的例子中,SBad 不是 聚合,因为类型 VStringSBad::s 不是 一个聚合,因为你为 VString 定义了一个构造函数。要使您的代码正常工作,请删除 VString:

的构造函数
 template <int W> class VString {
     char data[W];
 };

在这里试试:https://godbolt.org/z/TTonr6