Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 871
CodeBricks Avatar asked Jan 13 '23 23:01

CodeBricks


2 Answers

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.

like image 177
Cheers and hth. - Alf Avatar answered Jan 22 '23 06:01

Cheers and hth. - Alf


I tried your code in gcc version 4.5.3, when I compile, it gave the following error message: " error: declaration does not declare anything", what kind of compiler are you using? It is highly possible that you compiler does something under the hood.

like image 33
taocp Avatar answered Jan 22 '23 05:01

taocp