gpt4 book ai didi

c++ - 这些 vector 定义是 "constant initialization"吗?

转载 作者:搜寻专家 更新时间:2023-10-30 23:55:01 25 4
gpt4 key购买 nike

这个问题是关于代码的(在命名空间范围内):

std::vector<int> v1;
std::vector<int> v2(4);

在 C++14 (N4140) 的 3.6.2 节中定义了一个术语常量初始化:

Constant initialization is performed:

  • [omitted - about reference initialization]
  • if an object with static or thread storage duration is initialized by a constructor call, and if the initialization full-expression is a constant initializer for the object;
  • if an object with static or thread storage duration is not initialized by a constructor call and if either the object is value-initialized or every full-expression that appears in its initializer is a constant expression.

此外,constant initializer 一词刚刚在前面定义:

A constant initializer for an object o is an expression that is a constant expression, except that it may also invoke constexpr constructors for o and its subobjects even if those objects are of non-literal class types.

因此,查看 std::vector<int> v2(4) .

此对象由构造函数调用初始化,因此它包含在第二个要点中。初始化全表达式是4 . 4是一个常量表达式,因此它是一个常量初始化器。所以第二个要点得到满足,这应该是常量初始化的情况。

然而,我测试了几个编译器,它们似乎都处理 v2作为动态初始化

对于 v1情况下,不清楚这是否算作“由构造函数调用初始化”;如果是这样,初始化完整表达式会是什么。

我的问题是:是 v1v2 常量初始化,或者动态初始化;如果是后者,是否可以解释标准中的这些引用是如何解释的?

最佳答案

根据 1.9/10,初始化的完整表达式包括对构造函数的调用:

A full-expression is an expression that is not a subexpression of another expression. ... If a language construct is defined to produce an implicit call of a function, a use of the language construct is considered to be an expression for the purposes of this definition. ... Conversions applied to the result of an expression in order to satisfy the requirements of the language construct in which the expression appears are also considered to be part of the full-expression.
[ Example:
...

S s1(1); // full-expression is call of S::S(int)

然后,根据 8.5/17,直接初始化(v1v2 使用)涉及构造函数调用。

因此,根据您引用的第二个要点,构造函数调用是“初始化完整表达式”的一部分。所以构造函数调用,而不仅仅是 4,是完整的表达式。这反过来意味着这样的构造函数必须是 constexpr 才有资格作为 constant initializer(根据它的定义,正如你引用的那样)。由于 std::vector 的默认构造函数和 size_t 构造函数都不是 constexpr,因此初始化不是常量。

关于c++ - 这些 vector 定义是 "constant initialization"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34131331/

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