"" gives an empty string, while "".idup gives null
Steven Schveighoffer
schveiguy at yahoo.com
Wed Aug 3 10:15:51 PDT 2011
On Wed, 03 Aug 2011 06:35:08 -0400, simendsjo <simendsjo at gmail.com> wrote:
> void main() {
> assert(is(typeof("") == typeof("".idup))); // both is
> immutable(char)[]
>
> assert("" !is null);
> assert("".idup !is null); // fails - s is null. Why?
> }
An empty string manifest constant (i.e. string literal) still must have a
valid pointer, because it's mandated that the string have a zero byte
appended to it. This is so you can pass it to C functions which expect
null-terminated strings.
So essentially, there is a '\0' in memory, and "" points to that character
with a length of 0
However, idup calls a runtime function which *purposely* asks to make a
copy. However, it's *NOT* required to copy the 'zero after the string'
part.
The implementation, knowing that a null array is equivalent to an empty
array, is going to return null to avoid the performance penalty of
allocating a block that won't be used. If you append, it will simply
allocate a block as needed.
I see no reason the runtime should waste cycles or a perfectly good
16-byte buffer to give you an empty array.
Definitely functions as designed, not a bug. If you would like different
behavior, you are going to have to have a really really good use case to
get this changed.
-Steve
More information about the Digitalmars-d-learn
mailing list