"" gives an empty string, while "".idup gives null
Steven Schveighoffer
schveiguy at yahoo.com
Wed Aug 3 11:46:03 PDT 2011
On Wed, 03 Aug 2011 14:26:54 -0400, simendsjo <simendsjo at gmail.com> wrote:
> Schveighoffer also states it is as designed.
> But it really doesn't behave as one (at least I) would expect.
> So in essence (as bearophile says), "is null" should not be used on
> arrays.
>
> I was bitten by a bug because of this, and used "" intead of "".idup to
> avoid this, but given D doesn't distinguish between empty and null
> arrays, this doesn't feel very safe now..
I would recommend against depending on the difference between null and
not-null-but-empty arrays. But in any case, "".idup is mainly pointless,
there is never a need to idup a string, since it's already immutable (and
therefore can be passed wherever you need it).
> In the code in question I have a lazy initialized string. The problem is
> that I would see if it has been initialized, but an empty string is also
> a valid value. Because I shouldn't check for null, I now have to add
> another field to the struct to see if the array has been initialized.
> This feels like a really suboptimal solution.
Where is it that you need to use idup? I think you may be using that
without need (or if you are using code that violates immutability, that
code is incorrect), but I don't know what your code looks like so I might
be wrong.
In any case, there may be a better way to do what you want, without the
extra field.
At the very least, here is a function that can help you:
myIdup(string s)
{
return s.length == 0 ? "" : s.idup;
}
Note that this kind of thing *ONLY* works for strings, because string
literals are not null. For normal arrays, I wouldn't expect this to work.
-Steve
More information about the Digitalmars-d-learn
mailing list