4 ms·
Of course, there are benefits of GC: less development time, fewer null pointer exceptions, double free's and other other mistakes, etc
by ape4 5y ago
Of course, there are benefits of GC: less development time, fewer null pointer exceptions, double free's and other other mistakes, etc
- kragen 4y agoI don't see how GC reduces null pointer exceptions. If anything, GC encourages the use of pointers (as opposed to nested child objects), which increases null pointer exceptions.
- ape4 4y agoSometimes I code: { MyObject obj = new MyObject(); // Make an empty but non-null thing ... do stuff obj = new MyObject("real data"); } This would be bad in C++ of course, but in a GC language it avoids nulls.
- josephcsible 4y agoThat's bad in Java too: http://thecodelesscode.com/case/115 http://thecodelesscode.com/case/115
- ape4 4y agoI see wise Bazen's point. In theory that just replaces `if (obj != null) { ... }` with `if (obj.isInitialized()) { ... }` or similar nonstandard check. But it often makes for nicer and safer code.
- josephcsible 4y agoThat makes the code less safe, because now if you forget an isInitialized check, your code will silently do the wrong thing and start corrupting state, instead of failing early with a detailed stack trace and error.
- kragen 4y agoIn either Java or C++ it would be be better to write: { ... do stuff MyObject obj = new MyObject("real data"); } Except that in C++ to get the Java semantics you need an extra * in there. Where applicable, this converts the run-time NullPointerException into a compile-time error if you're referencing the value of obj before you've initialized it, which is an improvement. By contrast, your suggested change converts the run-time NullPointerException into silently incorrect behavior, which seems strictly worse in any context I've ever seen. You didn't say why your suggested change would be bad in C++, but I'm guessing you're thinking that it's because it would leak the initial empty object, which is true if you use a bare pointer. But in the more usual case where you just construct the empty object (as a "nested child object") in your stack frame MyObject obj; ... do stuff obj = MyObject("real data"); there's no leak and also no null pointers because no pointers at all. It's still bad in the same way your example is bad, though: if you read obj before you initialize it you still get incorrect results. (There's also no leak in C++ if you use a smart pointer.)