简体   繁体   English

C ++临时类实例化含糊不清

[英]C++ temporary class instantiation ambiguously

Let we have procedure formed as class. 让我们把程序形成为类。 Only constructor call makes some side effect. 只有构造函数调用会产生一些副作用。 No need to handle class instance in memory after call. 调用后无需在内存中处理类实例。 Following code instantiate that class: 以下代码实例化该类:

struct A{
    A(int){}
    };
int main() {

    A(0);//right. Pass const to ctor
    int x=0;
    A(x);//bad. Compiler interpret like A x;
    (A(x));//right. New temporary object passed to brackets
    A((int)x);//right. Pass temporary int to ctor

    return 0;
}

(see also on Online IDE ) (另请参阅在线IDE

Why A(x); 为什么A(x); interpret as variable x declaration instead of temporary A object instantiaton? 解释为变量x声明而不是临时对象实例?

From the C++11 standard, ISO/EIC 14882 §6.8 [stmt.ambig] ¶1 (emphasis mine): 从C ++ 11标准,ISO / EIC14882§6.8[stmt.ambig]¶1(强调我的):

There is an ambiguity in the grammar involving expression-statements and declarations: An expression-statement with a function-style explicit type conversion (5.2.3) as its leftmost subexpression can be indistinguishable from a declaration where the first declarator starts with a ( . In those cases the statement is a declaration. 在涉及表达式语句和声明的语法中存在歧义:具有函数式显式类型转换(5.2.3)的表达式语句 ,因为其最左侧的子表达式与第一个声明符以( a)开头的声明无法区分。 在这些情况下,该声明是一个声明。

To apply this to your question, A(x); 将此问题应用于您的问题, A(x); can parse as either "call the function A / construct a temporary object of type A , and pass x as the only function/constructor argument" or "declare a variable x of type A ." 可以解析为“调用函数A /构造类型A的临时对象,并将x作为唯一的函数/构造函数参数传递”或“声明类型A的变量x ”。 The standard says that in this case, it should be parsed as a variable declaration. 标准说在这种情况下,它应该被解析为变量声明。

Your other examples are not ambiguous because they cannot be parsed as a variable declaration, and so they are parsed as a call to A 's constructor. 您的其他示例不明确,因为它们不能被解析为变量声明,因此它们被解析为对A的构造函数的调用。

That's because what you consider should be the parameter list to the ctor, (x) is being interpreted as " x in parentheses". 那是因为您认为应该是ctor的参数列表, (x)被解释为“括号中的x ”。 Thus, A(x) is read as A (x) is read as A x . 因此, A(x)被读取为A (x)被读取为A x

In the other cases, the compiler has a hint suggesting that it should generate an A instance, calling the ctor with the arguments supplied. 在其他情况下,编译器有一个提示,表明它应该生成一个A实例,并使用提供的参数调用ctor。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM