Why doesn't the compiler warn about definitions without names?

The following C ++ code does nothing (using GCC 4.4.3) - it does not print text:

struct MyStruct { MyStruct() { cout << "Hello" << endl; } };

void foo() {
  MyStruct ();
}

I think this is not so obvious ... Not to mention the danger of forgetting to give a variable name. Is there a compiler option / warning to prohibit compilation of such code, or is there a hidden secret behind its permission?

Edit: Sorry. The version above MyStruct();completes printing. Version that does not print:

void bar() {
    MyStruct a();
}

So now I'm a little confused.

+3
source share
5 answers

, MyStruct (); MyStruct -specifier-seq . () -. , , . . -.

, . , , MyStruct.

Hello, , foo .


. , . , a. .

MyStruct a();

, , ,

a.f();

, -, "a" - , , MyStruct f, . , ? : return MyStruct, f.

a().f();

, , .

+6

" " . MyStruct(). , . , : ++ , / . ( , . ?)

+3

MyStruct a(); a, MyStruct.

+3

, [- ], c-tor.

Your code is syntactically perfect, so the compiler should not give a warning [as such].

EDIT [Subject to changes to OP]

MyStruct a ();

The above expression as a function declaration areturns an object MyStructand does not accept any parameters.

+2
source

Well, temporary objects are completely legal. Therefore, there is no reason to warn.

+1
source

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


All Articles