So sorry everyone. I meant for there to be an asterisk in the code I posted. Please answer again.
I'm doing a code review for a coworker, and I saw the following statement pop up:
if ((someClass *object1 = new someClass))
{
// Do work
}
Does this statement say the same as the following?
someClass *object1 = new someClass;
if (object1)
{
// Do work
}
I'm just trying to see if they are equal so we don't get any bugs.
You can't create an object inside an if
condition in the first form unless the type appear immediately inside the parenthesis, so:
if (someClass* object1 = new Someclass(...)) { ... }
Or, in general:
if (someType object1 = whatever) { ... }
if (someType object1{...constructor args}) { ... }
That syntactic detail aside - the main differences are that the above form uses the if
scope to control
the object1
variable's lifetime - the destructor will be invoked when the if
terminates (which might be important if your variable's controlling a resource, but pointers don't have destructors anyway so you'd need to ensure you call delete
before the if
scope finishes - do consider using a smart pointer), and
the object1
identifier itself, which can be freely used in the enclosing scope for some other unrelated variable.
In your second form the variable remains in scope after the if
's scope, and the identifier can't be reused until the end of the scope it's in.
The default of behaviour of new
is to throw an exception if it can't return a pointer to newly allocated memory, so the if
statement would only be skipped in that case, making the code equivalent to:
...
{
someClass* object1 = new SomeClass;
// other if content is effectively in a scope here
// to avoid a leak, must either:
- delete object1;
- copy/save the pointer somewhere to delete later
}
...
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