Why does nobody seem to think that `null` is a serious problem in D?
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Wed Nov 21 07:08:43 UTC 2018
On Tuesday, November 20, 2018 8:38:40 AM MST Kagamin via Digitalmars-d-learn
wrote:
> On Monday, 19 November 2018 at 21:23:31 UTC, Jordi Gutiérrez
>
> Hermoso wrote:
> > When I was first playing with D, I managed to create a segfault
> > by doing `SomeClass c;` and then trying do something with the
> > object I thought I had default-created, by analogy with C++
> > syntax.
>
> D is more similar to Java here and works like languages with
> reference types - Java, C#, Python, Ruby, JavaScript. Also AFAIK
> in C++ objects are garbage-created by default, so you would have
> a similar problem there. To diagnose crashes on linux you can run
> your program under gdb.
In C++, if the class is put directly on the stack, then you get a similar
situation to D's structs, only instead of it being default-initialized, it's
default-constructed. So, you don't normally get garbage when you just
declare a variable of a class type (though you do with other types, and
IIRC, if a class doesn't have a user-defined default constructor, and a
member variable's type doesn't have a default constructor, then that member
variable does end up being garbage).
However, if you declare a pointer to a class (which is really more analagous
to what you're doing when declaring a class reference in D), then it's most
definitely garbage, and the behavior is usually _far_ worse than
segfaulting. So, while I can see someone getting annoyed about a segfault,
because they forgot to initialize a class reference in D, the end result is
far, far safer than what C++ does. And in most cases, you catch the bug
pretty fast, because pretty much the only way that you don't catch it is if
that piece of code is never tested. So, while D's approach is by no means
perfect, I don't think that there's really any question that as far as
memory safety goes, it's far superior to C++.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list