gpt4 book ai didi

c++ - 返回具有未初始化成员的内联定义结构。 C++

转载 作者:太空狗 更新时间:2023-10-29 23:43:17 24 4
gpt4 key购买 nike

这个问题在论坛上受到的关注太少。

之前有人问过,但没有人捕捉到这个小细节。因此,我不确定自己是否做对了:

简单示例:

struct TEST {
bool a;
int b;
};

TEST func() {
return { false };
}

这是正确的吗?请注意,int 值未初始化。虽然将其设置为 0 不会有问题,但会出现更多问题:

struct _FILE_MUTEX {
bool locked;
HANDLE handle;
};

而且结构的最后一个成员可能会变得越来越复杂,从 vector 、数组到函数指针。

返回内联初始化结构时,我可以将一些成员留空吗?

最佳答案

这称为聚合初始化。

https://en.cppreference.com/w/cpp/language/aggregate_initialization

If the number of initializer clauses is less than the number of members and bases (since C++17) or initializer list is completely empty, the remaining members and bases (since C++17) are initialized by their default member initializers, if provided in the class definition, and otherwise (since C++14) by empty lists, in accordance with the usual list-initialization rules (which performs value-initialization for non-class types and non-aggregate classes with default constructors, and aggregate initialization for aggregates). If a member of a reference type is one of these remaining members, the program is ill-formed.

因此,在聚合初始化中,您允许提供的子句少于结构中的成员。每个没有默认初始化程序的剩余成员(例如 X)将被初始化为 X{}。

关于c++ - 返回具有未初始化成员的内联定义结构。 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54908516/

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