gpt4 book ai didi

c++ - 我可以访问临时对象的成员吗?

转载 作者:行者123 更新时间:2023-11-30 01:54:49 25 4
gpt4 key购买 nike

如果我使用 class-type-name(parameters).member 创建临时对象并假定构造函数已完成,我能否访问对象的成员?

考虑以下示例:

struct A
{
enum status
{ ERROR = -1, SUCCESS } state;
A (int a)
: state(a > 0 ? SUCCESS : ERROR)
{
// do some stuff here
// may change state
}
};

int main (void)
{
// Is this guaranteed to work?
A::status S(A(5).state);
}

A的构造函数是否需要在我访问state时立即完成?

最佳答案

是的,该标准要求实现在访问 state 之前执行 A 的构造函数的所有计算和副作用。


引用:

根据 C++11 的 5.2.5/1,表达式 X(Y).Z 是一个后缀表达式:

A postfix expression followed by a dot . or an arrow ->, optionally followed by the keyword template (14.2), and then followed by an id-expression, is a postfix expression.

表达式 X(Y) 根据同一段落计算:

The postfix expression before the dot or arrow is evaluated.64

64: If the class member access expression is evaluated, the subexpression evaluation happens even if the result is unnecessary to determine the value of the entire postfix expression, for example if the id-expression denotes a static member.

这就是 1.9/14 适用的地方:

Every value computation and side effect associated with a full-expression is sequenced before every value computation and side effect associated with the next full-expression to be evaluated.

因此,X(Y) 的计算和副作用在计算点运算符后立即完成。

然而,根据 5.2.3/1,此表达式生成一个完全构造的对象 X:

[...] the expression T(x1, x2, ...) is equivalent in effect to the declaration T t(x1, x2, ...); for some invented temporary variable t, with the result being the value of t as a prvalue.

和 12.2/3:

When an implementation introduces a temporary object of a class that has a non-trivial constructor (12.1, 12.8), it shall ensure that a constructor is called for the temporary object. [...] Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created.

标准要求程序以这种方式运行,即使尚未执行临时对象的实际创建 (12.2/1):

Even when the creation of the temporary object is unevaluated (Clause 5) or otherwise avoided (12.8), all the semantic restrictions shall be respected as if the temporary object had been created and later destroyed.

关于c++ - 我可以访问临时对象的成员吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21554577/

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