gpt4 book ai didi

c++ - 像 "Foo(12,3);"这样的未命名变量的强制构造仍然是声明符吗?

转载 作者:搜寻专家 更新时间:2023-10-31 01:02:54 24 4
gpt4 key购买 nike

考虑以下简单示例:

struct A 
{
int a;
A(int b);
};

A *p;

A::A(int b) : a(b)
{
p = this;
std::cout << "A()" << std::endl;
}



int main()
{
A(10); //What is it?
std::cout << p -> a << std::endl; //10
}

我不确定 N3797::8.5 [dcl.init] 是否可以应用在这里,因为 N3797::8.5/1 [dcl.init] 说:

A declarator can specify an initial value for the identifier being declared. The identifier designates a variable being initialized

在没有声明者的情况下。这意味着该规则不适用。

如果它只是一个构造函数调用,它在哪里指定 int 标准,即 class-name(argument_list) 形式的表达式分配合适数量的内存(哪个分配函数接管了它?)和初始化一个对象?我希望获得有关此类表达式如何工作的更多详细信息?

最佳答案

A(10);

这是一个丢弃值表达式。根据 [expr.type.conv],

A simple-type-specifier (7.1.6.2) or typename-specifier (14.6) followed by a parenthesized expression-list constructs a value of the specified type given the expression list. If the expression list is a single expression, the type conversion expression is equivalent (in definedness, and if defined in meaning) to the corresponding cast expression (5.4).

'对应的转换表达式'是(A)10 ,这又相当于 static_cast<A>(10) ([expr.cast]/4),以及 static_cast定义为 [expr.static.cast]/4:

Otherwise, an expression e can be explicitly converted to a type T using a static_cast of the form static_cast<T>(e) if the declaration T t(e); is well-formed, for some invented temporary variable t (8.5). The effect of such an explicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion.

这就是你的声明符。

关于c++ - 像 "Foo(12,3);"这样的未命名变量的强制构造仍然是声明符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26323471/

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