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?
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!
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.
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