在声明中仅使用类名尝试构造临时对象

Cod*_*cks 4 c++ constructor declaration uniform-initialization c++11

C++

cout构造和销毁此类消息的对象.我试图使用只有类名的声明来构造一个临时对象,但它给出了一个意外的输出.

在#1中,我使用括号实例化一个临时无名对象.

在#2中,我使用统一初始化实例化一个临时无名对象.

我不知道#3是否会编译.我只想到如果编译#3,它将表示临时无名对象的构造.它确实编译,但是从#3下控制台输出的空白处看不到构造对象.这里发生了什么?

#include <iostream>

class A
{
public:
    A() {std::cout << "constructed\n";}
    ~A() {std::cout << "destroyed\n";}
};

auto main() -> int
{
    std::cout << "#1:\n";
    A();
    std::cout << "#2:\n";
    A{};
    std::cout << "#3:\n";
    A;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

控制台输出:

#1:
constructed
destroyed
#2:
constructed
destroyed
#3:
Run Code Online (Sandbox Code Playgroud)

注意:这是在2012年11月CTP的VC11中编译的.它不能在g ++ 4.8.0或clang 3.2中编译,它们分别给出error: declaration does not declare anything [-fpermissive]fatal error: 'iostream' file not found.

Che*_*Alf 5

所有C++标准(C++ 98,C++ 03,C++ 11)下的代码都是无效的,不应编译.

类型不是声明.

事实上,Visual C++和g ++都没有编译它:

哎呀,虽然g ++正确地诊断了程序,但2012年11月的Visual C++ CTP却没有:

[D:\dev\test]
> (cl 2>&1) | find /i "C++"
Microsoft (R) C/C++ Optimizing Compiler Version 17.00.51025 for x86

[D:\dev\test]
> cl /nologo /EHsc /GR /W4 foo.cpp
foo.cpp

[D:\dev\test]
> g++ -std=c++0x -pedantic -Wall foo.cpp
foo.cpp: In function 'int main()':
foo.cpp:17:5: error: declaration does not declare anything [-fpermissive]

[D:\dev\test]
> _

所以这是一个编译器错误,您可以尝试在Microsoft Connect上报告它.