Empty return in Constructor
I expected Visual Studio to give me an error or at the very least a warning, but it gave me neither when I had an empty return
in the constructor:
MyObject::MyObject()
{
if (/*some condition*/)
{
//SomeCode
ret开发者_如何转开发urn;
}
// continue with other code
}
I have not seen usage of this so far in my limited experience, so my question is whether it is OK to have a return in the constructor?
This is more of a curiosity question as I understand that it is very easy to code such that you never have to put return in there, although I have an instance where this would be very useful, but before using it I want to see if it is prohibited (maybe by the standard or is, in general, not a good idea).
The standards say:
12.1 Constructors
...
A return statement in the body of a constructor shall not specify a return value. The address of a constructor shall not be taken.
...
It is OK to have return;
in a constructor. My understanding is that this was allowed so that the programmer can return early from the constructor without the need for making a mess with boolean flags.
It's ok. It means the object has been constructed successfully. It should not bite you if you follow the general advice of initializing member variables in the initializer list. It's similar to the innocent looking following code.
MyObject::MyObject () {
if (/* something */) {
// SomeCode
} else {
// continue with other code
}
}
精彩评论