"int (x), 1;" 是模棱两可的说法吗?

Is "int (x), 1;" an ambiguous statement?

void f(int x) {
    int (x), 1;
}

Clang 会编译它,GCC 不会。哪个编译器是正确的?

海事组织,[stmt.ambig]中的措辞已经足够清楚了:

An expression-statement with a function-style explicit type conversion 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.

[Note: If the statement cannot syntactically be a declaration, there is no ambiguity, so this rule does not apply. The whole statement might need to be examined to determine whether this is the case.

措辞代表了整个(表达式)语句。 你的陈述不能被解析为声明,因为词素 1 在语法上不是 声明符 。没有歧义:如果我们只看 int(x),它可能看起来有歧义,但标准非常明确地否认,如果语句的某些前缀被解析为声明,则整个语句被认为是潜在的声明。

事实上,早在 2002 年,核心专家就 core issue 340 进行了高度相似的讨论——我强调了重要的部分。在这里,我们有一个假设的声明,其中包含一个不兼容的子结构。

Consider the following program:

struct Point   {
  Point(int){}   
};
struct Lattice    {
  Lattice(Point, Point, int){}   
};
int main(void)   {
  int a, b;
  Lattice latt(Point(a), Point(b), 3);   /* Line X */   
} 

The problem concerns the line marked /* Line X */, which is an ambiguous declarations for either an object or a function. The clause that governs this ambiguity is 8.2 [dcl.ambig.res] paragraph 1, and reads:

The ambiguity arising from the similarity between a function-style cast and a declaration mentioned in 6.8 [stmt.ambig] [..]

基于这个条款有两个 X:

行声明的可能解释
  • latt 的声明声明了一个具有 return 值的函数 输入 Lattice 并接受三个参数。前两个的类型 arguments 是 Point 并且每个参数后跟一个 多余括号中的参数名称。第三种类型 无法确定参数,因为它是文字。 这将 导致语法错误。
  • latt的声明声明了一个对象, 因为另一个选项(函数声明)会导致 语法错误。请注意,“[注意:”之前的最后一句话不是 很有帮助,因为这两个选项都是声明。

Steve Adamczyk:很多人在 comp.std.c++表示没看出问题

原文 发帖人回复:

我只能同意你的论点。所以有 只有一个对第 8.2 条的正确解释 [dcl.ambig.res] 第 1 段,但我不得不说,经过一些改写,该条款 可以变得更清楚,比如明确说明整个 必须考虑声明,并且函数声明 优先于对象声明。

我想建议以下内容作为当前的替代品 第 8.2 条 [dcl.ambig.res] 第 1 段:

The ambiguity arising from the similarity between a functionstyle cast and a declaration mentioned in 6.8 [stmt.ambig] […]

工作组觉得现在的措辞已经足够清楚了。