gpt4 book ai didi

c++ - 混合内联和构造函数初始化的初始化顺序

转载 作者:行者123 更新时间:2023-12-04 00:13:05 25 4
gpt4 key购买 nike

[此问题源于this question ]

考虑以下程序:

#include <iostream>

struct Foo
{
const size_t size;
int* arr{ create_arr(size) };

Foo(size_t s)
: size{ set_size(s) }
{
}

static int* create_arr(size_t s)
{
std::cout << "Creating array with size " << s << '\n';
return new int[s];
}

static size_t set_size(size_t s)
{
std::cout << "Setting size to " << s << '\n';
return s;
}
};

int main()
{
Foo f(10);
}

arr 的内联初始化依赖于size 的值。但是size的值只在构造函数初始化列表中初始化。

Both GCC and Clang handles it correctly , 如果 sizearr 的声明顺序被镜像,则会报错。我还听说 MSVC 会做“正确”的事情(根据 the other question 中的评论)。

我的问题是:这是明确定义的吗?

我知道初始化是按声明顺序完成的,但它是否也包括内联初始化?

最佳答案

I know that initialization is done in declaration order, but does itinclude inline initialization as well?

是的,必须,见 class.base.init :

13 In a non-delegating constructor, initialization proceeds in thefollowing order: (13.1) — First, and only for the constructor of themost derived class (4.5), virtual base classes are initialized in theorder they appear on a depth-first left-to-right traversal of thedirected acyclic graph of base classes, where “left-to-right” is theorder of appearance of the base classes in the derived classbase-specifier-list. (13.2) — Then, direct base classes areinitialized in declaration order as they appear in thebase-specifier-list (regardless of the order of the mem-initializers).(13.3) — Then, non-static data members are initialized in the orderthey were declared in the class definition (again regardless of theorder of the mem-initializers). (13.4) — Finally, thecompound-statement of the constructor body is executed. [ Note: Thedeclaration order is mandated to ensure that base and member sub

虽然这里的标准不是太具体,但这应该是完全足够的,因为默认的成员初始化器是初始化器。类定义中的顺序始终是这里的基础。在初始化方面,这里有一个异常(exception)与标准的许多其他部分极为矛盾。

在本节中还有一个附加说明,该标准通过对破坏的关注强调了这一点:

[ Note: The declaration order is mandated to ensure that base andmember subobjects are destroyed in the reverse order ofinitialization. — end note ]

所以这里根本没有进一步解释的余地​​。

关于c++ - 混合内联和构造函数初始化的初始化顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66635787/

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