程序在3个主要的C ++编译器中编译不同。哪一个是正确的? [英] Program being compiled differently in 3 major C++ compilers. Which one is right?

查看:323
本文介绍了程序在3个主要的C ++编译器中编译不同。哪一个是正确的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个有趣的后续(不是很大的实际重要性,虽然)我的上一个问题:
为什么在声明变量时,C ++允许我们在括号中包围变量名?

As an interesting follow-up (not of big practical importance though) to my previous question: Why does C++ allow us to surround the variable name in parentheses when declaring a variable?

我发现将括号中的声明与注入类名功能可能会导致关于编译器行为的令人惊讶的结果。

I found out that combining the declaration in parentheses with injected class name feature may lead to surprising results regarding compiler behavior.

查看以下程序:

#include <iostream>
struct B
{
};

struct C
{
  C (){ std::cout << "C" << '\n'; }
  C (B *) { std::cout << "C (B *)" << '\n';}
};

B *y = nullptr;
int main()
{
  C::C (y);
}




  1. 使用g ++编译4.9.2给出以下编译错误:

  1. Compiling with g++ 4.9.2 gives me the following compilation error:

main.cpp:16:10: error: cannot call constructor 'C::C' directly [-fpermissive]


  • 它与MSVC2013 / 2015成功编译并打印 C(B *)

    它使用clang 3.5编译成功并打印 C

    It compiles successfully with clang 3.5 and prints C

    因此,强制性问题是哪一个是正确的? :)

    So obligatory question is which one is right? :)

    (我强烈地摇摆的clang版本虽然和msvc方式停止声明变量后只是改变类型,技术上它的typedef似乎很奇怪) em>

    (I strongly swayed towards clang version though and msvc way to stop declaring variable after just changing type with technically its typedef seems kind of weird)

    推荐答案

    GCC是正确的,至少根据C ++ 11查找规则。 3.4.3.1 [class.qual] / 2指定,如果嵌套的名称说明符与类名称相同,则它引用构造函数而不是注入的类名称。它给出了例子:

    GCC is correct, at least according to C++11 lookup rules. 3.4.3.1 [class.qual]/2 specifies that, if the nested name specifier is the same as the class name, it refers to the constructor not the injected class name. It gives examples:

    B::A ba;           // object of type A
    A::A a;            // error, A::A is not a type name
    struct A::A a2;    // object of type A
    



    看起来像MSVC误解为函数式转换表达式创建一个临时 C y 作为构造函数参数;和Clang将其解释为对 C 类型的 y 变量的声明。

    It looks like MSVC misinterprets it as function-style cast expression creating a temporary C with y as a constructor parameter; and Clang misinterprets it as a declaration of a variable called y of type C.

    这篇关于程序在3个主要的C ++编译器中编译不同。哪一个是正确的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆