Memory safe in D
ShowMeTheWay
ShowMeTheWay at gmail.com
Tue Apr 16 22:15:42 UTC 2024
On Tuesday, 16 April 2024 at 15:51:11 UTC, bachmeier wrote:
>
> ...
> That should say there's no good argument in favor of the first
> line in your example compiling. The compiler should stop as
> soon as it sees `A a;`.
I have to disagree here.
If A is a class definition, then:
A a;
is valid code, even though the compiler initialises it to null
here, by default.
null is a valid state for a.
The programmer might prefer to assign to it separately, for
example:
a = new A();
In this case:
a.run();
cannot be considered a likely bug, since 'a' has been assigned to
before before it is used.
So the bug is not that 'a' is null (cause that is a valid state
for 'a'), but that 'a' is being used before it has been assigned
to.
Now if the programmer did:
A a = null; // definitely assigned
a.run();
.. then the programmer is an idiot, and the compiler should let
the programmer deal with the consequences ....
Coming from C# or Java, it must feel like coming to D means going
backwards with regards to the compilers ability to detect simple
bugs like this.
Coming from a C++ background is even worse perhaps, cause a C++
may well think that 'A a;' actually calls the objects
constructor... a mistake I made lot early on with D, and still do
on occasion (and the compiler is no help at all here).
D will always accept 'A a;' as valid code, I expect.
What the D compiler really needs however, is some simple definite
assignment analysis (for local variables) to detect a simple bug
like this... perhaps as a compile time argument initially... but
eventually made the default.
I doubt it would be difficult or complex to implement (for
someone who knows how to).
So really, the only question is what impact it would have on
compile time.
If it's only for local variables, then that impact should not
really be noticable.
btw. This too is a likely bug:
int b;
writeln(b);
The compiler should require you to assign to 'b' before using it.
On the otherhand, this below should *not* get the compilers
attention:
int b = int.init;
writeln(b);
More information about the Digitalmars-d
mailing list