## Recommended Posts

I have an object that may end up returning a null reference:

object O1 ("foo"); // O1 is null
object @O2 = @O1;  // all ok!

This works fine: both O2 and O2 are null. So surely I can join those statements together?

object @O3 = object ("foo"); // nullptr error

But no, that doesn't work: in this case the script aborts with a nullptr error. Am I doing something wrong? Am I just misunderstanding how it is supposed to work? Is it ok to return null from a constructor? It's doing a lookup for an object with id 'foo', which may or may not exist...

Thanks for any enlightenment offered!

##### Share on other sites

Seems weird to me, to return null from a constructor/factory function. Why do you need to do that? Why not just use a normal function?

##### Share on other sites

I think the reasoning more or less went like this: "In C++ I'd just make a constructor and then throw when I can't get the resource... Angelscript doesn't have exceptions (back then)... Ah wait, it lets me return a nullptr instead so it's all good."

The whole development cycle happened under a lot of time pressure, unfortunately, so once I had something that worked, I didn't spend too much time playing around with it to see if there was a better option. Of course that's now coming back to bite me... And we did this for an external customer, so I should endeavour to keep the interface stable.

Anyway, it's kinda surprising that the two snippets I posted aren't equivalent.

##### Share on other sites

It looks like you've exploited an undefined behaviour in the past.

I will take a look at this, to see what can be done. However, I'd say that the first case is the one that is wrong, not the second one. A factory shouldn't be allowed to return null without also calling SetException to indicate the failure to create the object instance.

##### Share on other sites

Ok, thanks for the info. I'll make the necessary changes to ensure I'm not invoking UB. Could I do this instead:

object @O = makeobject ("foo");

and have that potentially return a nullptr?

##### Share on other sites

Yes, that's perfectly fine.

## Create an account

Register a new account

• ### Game Developer Survey

We are looking for qualified game developers to participate in a 10-minute online survey. Qualified participants will be offered a \$15 incentive for your time and insights. Click here to start!

• 9
• 56
• 17
• 28