C++
Objects of this class cout
s 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With