3 ms·
(Tangential) Got to scratch my head at this "authoritatively voiced" bit of advice in the SO thread: > Testing the result of a constructor in any language is p
by sk5t 5y ago
(Tangential) Got to scratch my head at this "authoritatively voiced" bit of advice in the SO thread:
> Testing the result of a constructor in any language is probably a dodgy practice. It's an object or it's a 'null'.
Ah, if there's an OO language anywhere that can return null from a constructor invocation, I have yet to see it.
- thom 5y agoDunno if this counts but it’s not unheard of to return nil from init methods in Objective-C.
- hugey010 5y agoYep, afaik if allocation of memory for the object fails it's canonical to immediately return nil.
- pwdisswordfish8 5y agoC++ with new(std::nothrow)?
- kevingadd 5y agoC# constructors technically don't return anything (afaik), the object is allocated and then the constructor is invoked on it. So it's theoretically possible for your compiled code to produce a null as the result of a 'new' expression. I think this wouldn't be spec compliant though, since the two scenarios where this would make sense (OOM and exception thrown during alloc or ctor) should just throw and unwind before you can see observe the null or uninitialized instance. FWIW, it's also possible to enter an instance method with a null 'this' under certain circumstances (normally there would be a null reference check before entering the method body, but I've run into cases where there wasn't) Contrived scenario: You AOT-compile your code in a 'no exceptions' mode, so the generated code assumes that malloc can't throw, etc. In that case if a failure happens during the 'new' process the only reasonable return values are either null or an instance with garbage data in it. As a compiler author, out of the two I'd probably pick null. This isn't as far-fetched as it sounds since right now exception handling in WebAssembly is a nightmare. Actually, I wonder if an exception filter could observe the null before the unwind happens...
- benibela 5y agoDelphi/Pascal has 2-layered constructors. There is a virtual class method to allocate memory and a so called constructor that initializes fields that should be zero. The user of a class, only calls the constructor. The constructor then calls the memory-allocation method implicitly (you can see the call with a disassembler, but not in the Pascal code). Anyways, you can override the memory-allocation method for each class. E.g. a useful case would be to build an arena allocator just for that class. But you can also override it, so that calling the class constructor returns a null