Finding out about D - 101

Steve Teale steve.teale at britseyeview.com
Mon May 11 09:42:17 PDT 2009


OK, so let's find out about strings. D does not have 'string' as a built in type. It is just an alias for invariant(char[]). So what is it?

Well, you can find out quite a bit by compiling and running:

import std.stdio;

struct S
{
   size_t len;
   void* p;
   int xtra;
}

void main()
{
   string a;
   string b = "";
   char[] ca = ['a','b','c','d'];
   string c = "abcd";

   writefln("(a == b) %s", (a == b));

   S* s = cast(S*) &b;

   writefln("a: [%s] %s %08x, %d", a, (a is null), a.ptr, a.length);
   writefln("b: [%s] %s %08x, %d", b, (b is null), b.ptr, b.length);

   writefln("b as S: [%08x] %d [%08x]", s.p, s.len, s.xtra);
   writefln("char at *b.ptr = [%s] (%d)", *b.ptr, cast(ubyte) *b.ptr);
   s = cast(S*) &ca;
   writefln("ca as S: [%08x] %d [%08x]", s.p, s.len, s.xtra);
   s = cast(S*) &c;
   writefln("c as S: [%08x] %d [%08x]", s.p, s.len, s.xtra);
}

This tells me that a string in D is a sequence of characters (whatever that might mean) in memory, prefixed by a size_t length. Of  course, that's not to say there is no more to it, but the values for 'xtra' don't give us much clue. If there was some other member of struct S, I'd kind of expect to see bit flags there indicating whether the array of char was invariant, const, or fair game.

So I'm left with the question as to how does 'invariant' have teeth?



More information about the Digitalmars-d-learn mailing list