gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:56:58 25 4
gpt4 key购买 nike

我想知道如何初始化结构的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com