Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Creation point" of automatic variable

void foo()  
{  
    //some code

    MyClass m();

    //some more code
}

Does the C++ standard ensure that the constructor of class MyClass will be called after //some code has run, or is it unspecified behavior?

like image 695
Boaz Avatar asked Feb 21 '23 11:02

Boaz


2 Answers

The technical answer to this question is that the compiler will guarantee that the constructor isn't run at all, because the line

MyClass m();

is not a variable declaration. Instead, it's a prototype for a function called m that takes no arguments and returns a MyClass. To make this into an object, you need to drop the parens:

MyClass m;

Because this is such a source of confusion, in C++11 there is a new syntax you can use for initializing automatic objects. Instead of using parentheses, use curly braces, like this:

MyClass m{};

This tells the compiler to use the nullary constructor for MyClass as intended, since there's no way to interpret the above as a function prototype.

If you make this change, the compiler will guarantee that m's constructor is executed after the first piece of code and before the second piece of code.

Hope this helps!

like image 190
templatetypedef Avatar answered Feb 24 '23 02:02

templatetypedef


First of all MyClass m(); doesn't create any object, you probably meant MyClass m;. Yes, it is guaranteed that the object is created only after //some code is ran.

like image 31
Naveen Avatar answered Feb 24 '23 01:02

Naveen