Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "new" and "if" statements together - syntax related

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.

like image 458
Lawrence Aiello Avatar asked Dec 25 '22 23:12

Lawrence Aiello


1 Answers

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 
}
...
like image 188
Tony Delroy Avatar answered Jan 05 '23 18:01

Tony Delroy