Search code examples
c++c++11constructordeclarationuniform-initialization

Attempted construction of temporary object using only class name in declaration


C++

Objects of this class couts messages when they are constructed and destroyed. I tried to construct a temporary object using a declaration of only the class name, but it gave an unexpected output.

In #1, I instantiate a temporary nameless object using parentheses.

In #2, I instantiate a temporary nameless object using uniform initialization.

I didn't know whether #3 would compile. I only thought that if #3 were to compile, it would signify a construction of a temporary nameless object. It does compile, but no object is constructed as seen from the blankness of the console output under #3. What is happening here?

#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;
}

Console Output:

#1:
constructed
destroyed
#2:
constructed
destroyed
#3:

Note: This was compiled in VC11 with November 2012 CTP. It doesn't compile in g++ 4.8.0 or clang 3.2, which gives error: declaration does not declare anything [-fpermissive] and fatal error: 'iostream' file not found, respectively.


Solution

  • The code is invalid under all C++ standards (C++98, C++03, C++11) and should not compile.

    A type is not a statement.

    And indeed neither Visual C++ nor g++ compiles it:

    Oops, while g++ correctly diagnoses the program, the November 2012 CTP of Visual C++ does not:

    [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]
    > _
    

    So this is a compiler bug, and you can try to report it at Microsoft Connect.