Trying to create a temporary object using only the class name in the declaration

C ++

Objects of this class cout messages when they are created and destroyed. I tried to create a temporary object using only the class name declaration, but it gave an unexpected result.

In # 1, I create a temporary unnamed object using parentheses.

In # 2, I create a temporary nameless object using a single initialization.

I did not know if compilation # 3 would be. I only thought that if No. 3 would compile, this would mean creating a temporary nameless object. It compiles, but the object is not created, as can be seen from the emptiness of the console output at # 3. What's going on 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 exit:

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

Note: This was compiled in VC11 with the November 2012 CTP. It does not 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.

+4
source share
3 answers

The code is not valid for all C ++ standards (C ++ 98, C ++ 03, C ++ 11) and should not be compiled.

Type is not an expression.

And by no means does Visual C ++ or g ++ compile it:

Unfortunately, while g ++ correctly diagnoses the program, November 2012 CTP 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 error, and you can try to report it to Microsoft Connect .

+5
source

I tried your code in gcc version 4.5.3, when I compile, it gave the following error message: "error: declaration declares nothing", which compiler are you using? It is very possible that your compiler is doing something under the hood.

+2
source

both g++ and clang throw an error 17:5: error: declaration does not declare anything

No matter which compiler you use, the line can be fully optimized, but this is just speculation. What are you compiling with?

This is not a legal afayk. just like int; not a legal statement.

+2
source

Source: https://habr.com/ru/post/1469115/


All Articles