bug?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Sep 15 15:15:49 PDT 2016


On Thursday, September 15, 2016 18:15:52 deed via Digitalmars-d-learn wrote:
> I'm curious when you would need to do only `new Struct[](1000);`
> instead of
> `auto structs = new Struct[](1000);`?

Need to do? Probably never. It would be a pretty weird thing to do. But if
Struct has a destructor that actually does stuff, then

    new Struct[](1000);

does not have no effect. Because the array is allocated on the GC heap, it's
unknown when the destructors will run (and they may not ever actually run,
because they'll only be run if a collection is run, and it collects that
array), but it's still the case that removing that line will potentially
change what the program does beyond just perfomance.

For instance, as dumb as it would be, the destructor for Struct could do
something like send an e-mail when it's run, and so if the compiler
optimized out the array of Structs being allocated, those e-mails would not
be sent, and the behavior of the program would change substantially.

It would be a pretty rare case where it actually made sense for the
programmer to just allocate an array like that and the let it go away. But
the compiler has no way of knowing what the programmer intended. And if
there's code that's actually run as a result of that line, then it's not
true that it doesn't have any effect, and creating an error over it would be
a bit much. Some compilers might warn about it, because the odds are very
high that it was not intended, but Walter isn't big on warnings, and dmd
didn't even have any for a long time - though he eventually did get worn
down enough by requests for them that he gave in and added a few.

The problem with warnings is that it's bad practice to leave warnings in
your code (otherwise, it becomes way to easy to miss legitimate things that
you've been warned about). And if you're not leaving warnings in your code,
then they're really not any different from errors except for the fact that
you don't have to immediately fix them to get your code to compile. So,
arguably, warnings are pretty pointless, and that sort of thing is better
left to a linter tool.  And something like _that_ probably would warn about
code like this, because the odds are quite high that it's not what you meant
to do.

In general though, dmd tends to tell you when you did something definitely
wrong but not say anything when you did something that you probably didn't
mean to do but was perfectly legal.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list