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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The technical answer to this question is that the compiler will guarantee that the constructor isn’t run at all, because the line
is not a variable declaration. Instead, it’s a prototype for a function called
mthat takes no arguments and returns aMyClass. To make this into an object, you need to drop the parens: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:
This tells the compiler to use the nullary constructor for
MyClassas 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!