Forbid dynamic arrays in boolean evaluation contexts
Timon Gehr
timon.gehr at gmx.ch
Mon Mar 25 10:05:10 PDT 2013
On 03/24/2013 11:10 PM, bearophile wrote:
> A recent discussion in D.learn reminds me of an enhancement request of
> mine that is sleeping in Bugzilla since years:
>
> http://d.puremagic.com/issues/show_bug.cgi?id=4733
>
>
> The probles is that in D dynamic arrays can be non-null even when they
> are empty:
>
>
> import std.stdio;
> int[] foo() {
> auto a = [1];
> return a[0..0];
> }
> void main() {
> auto data = foo();
> if (data)
> writeln("here");
> }
>
>
> This is dangerous, so in D the safe and idiomatic way to test for empty
> arrays is to use std.array.empty().
>
> So my proposal of Issue 4733 is to forbid (with the usual
> warning/deprecation intermediate steps) the use of dynamic arrays in a
> boolean context:
>
>
> void main() {
> auto a = [1];
> if (a) {} // error, forbidden.
> }
>
>
> So to test empty/null you have to use empty() or "is null":
>
> import std.array: empty;
> void main() {
> auto a = [1];
> if (a.empty) {} // OK
> if (a is null) {} // OK
> }
> ...
Well, cast(bool)a currently checks a.ptr:
void main(){
auto x = (cast(void*)null)[0..1];
assert(x !is null);
assert(x);
}
Also, IMO null arrays should either be removed or [] should be
guaranteed to be non-null.
Maybe cast(bool)a simply shouldn't work. (though, personally, I'd lean
towards checking length.)
More information about the Digitalmars-d
mailing list