3 ms·
In either Java or C++ it would be be better to write: { ... do stuff MyObject obj = new MyObject("real data"); } Except that in C++ to
by kragen 5y ago
In 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.)