C++ 使用值初始化聚合类型的 std::array

标签 c++ c++11 initialization stdarray

我想知道如何初始化结构的 N 元素 std::array。

例子:

struct SomeStruct {
  uint32_t * const entry1;
  uint16_t * const entry2;
  uint16_t * const entry3;
};

可以通过以下方式进行初始化:

static const std::array<SomeStruct , 2> arr
{nullptr, nullptr, nullptr, nullptr, nullptr, nullptr};
// nullptr just for example, would be addresses of real variables in the project

但这并不是我所需要的,因为下面的语句在没有任何警告或其他任何东西的情况下也能正常工作,因此使元素默认初始化。

static const std::array<SomeStruct , 2> arr
{nullptr, nullptr, nullptr, nullptr};

我需要的是对编译器进行严格检查,是否所有元素都已初始化,语法类似于:

static const std::array<SomeStruct , 2> arr
{{nullptr, nullptr, nullptr}, {nullptr, nullptr, nullptr}};

是否可以强制 C++ 检查聚合类型的所有元素是否已初始化?

加油!

最佳答案

But this is not exactly what I need because the following statement works as well without any warning or something else, and therefore leaves elements default initilized.

它不会让元素默认初始化。 aggregate initialization 上的 cppreference ,强调我的:

If the number of initializer clauses is less than the number of members or initializer list is completely empty, the remaining members are value-initialized. If a member of a reference type is one of these remaining members, the program is ill-formed.

C++11 中的确切措辞发生了变化,但不会影响您的情况。

所以,如果你想将所有初始化为nullptr,只需使用

static const std::array<SomeStruct , 2> arr{};

如果您希望在任何元素未明确初始化时发出警告,那么您没有可移植的解决方案。编译器无法知道数组其余部分的值初始化是否是有意的。

不可移植的解决方案:GCC 有一个警告标志 -Wmissing-field-initializers

warning: missing initializer for member 'SomeStruct::entry2' [-Wmissing-field-initializers]

{nullptr, nullptr, nullptr, nullptr};
                                   ^

关于C++ 使用值初始化聚合类型的 std::array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41975660/

相关文章:

c++ - boost 正则表达式 : Getting the Named Group

c++ - 交叉编译中的 CMake CMAKE_AUTOMOC

c++ - 为什么模板只能在头文件中实现?

c++ - 将类模板转换为 SFINAE 和构造函数委托(delegate),现在出现编译器错误

C++ 结构初始化

c++ - 重载 (c)begin/(c)end

c++ - 如何正确使用 vector 范围构造函数?

c++ - 复制 vector 对

C++ : 3 questions about initialization syntax, 值初始化和默认初始化

c++ - Centos6 gcc6 : default ABI not picked up when compiling simple c++11 test file