"" gives an empty string, while "".idup gives null

Jonathan M Davis jmdavisProg at gmx.com
Wed Aug 3 11:41:22 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.

Given that if you really wanted the duped string to be empty instead of null, 
it wouldn't be very hard to write a wrapper function for dup which did that, 
I'd be _very_ surprised if you could find a use case where dup should allocate 
for an empty string.

I don't generally like the fact that D tends to conflate null and empty, but 
you're creating a new array here. It's not at all surprising if it ends up 
null if it has no elements in it. In general though, you need to be fairly 
careful about where you rely on the difference between empty and null. If any 
kind of memory allocation occurs to an array and its length is 0, it's pretty 
much free game as to whether it's empty or null.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list