String convention

Jarrett Billingsley kb3ctd2 at yahoo.com
Sat Jul 1 17:01:09 PDT 2006


"Niklas Ulvinge" <Niklas_member at pathlink.com> wrote in message 
news:e86qp9$1e3t$1 at digitaldaemon.com...
> Thanks for all replies, now I understand most of what I wanted to know.
> (although the Q about the internal structure of dynamic arrays still 
> remains...)

OK.

This is the definition for a char[].  This is the same for ALL array types 
in D, not just strings; just replace "char" with any other type, and it's 
the same.

struct CharArray
{
    private size_t _length = 0;
    private char* _ptr = null;

    public size_t length(size_t l)
    {
        if(_ptr is null && l > 0)
            _ptr = malloc(char.sizeof * l);
        else
        {
            if(l > _length)
                _ptr = realloc(_ptr, char.sizeof * l);
        }

        _length = l;

        return _length;
    }

    public size_t length()
    {
        return _length;
    }

    public char* ptr()
    {
        return _ptr;
    }
}

There are other methods, such as .dup and .sort, but I won't list them.

When you write

char[] s;

You get

CharArray s;

It has length 0 and pointer null.

So you set its length:

s.length = 5;

This actually means "s.length(5)".  This is because of the property syntax 
in D.

So it allocates enough space for 5 characters.

Is that satisfactory?

> The foreach statemente as an example.
> In D, the compiler handles the implementation.
> I want to know how it is implemented.

You worry too much about things that you shouldn't care about.

But if you really must know, foreach is implemented as a nested function for 
the actual foreach body.  You can see kind of how it works by looking up how 
to overload opApply.

> In languages where "a" + "b" = "ab" works there could be programmers who 
> doesn't
> see that concating is much more complex than adding a couple of numbers.
> In D, this is a little better, becouse it's hard to find the concating 
> char (I
> don't have it now, becouse of an odd bug in firefox).
> In C/C++ this is better, becouse it was a func, wich indicated how hard it 
> was
> to do.

Not for std::string; that used + for string concatenation.  Sure hides the 
implementation details.

> Some programmers may instead of using:
> writef(a,b,c)
> concate them. Wich would be very bad.

Unless you really _need_ to concatenate strings, such as to store in a new 
string. 





More information about the Digitalmars-d mailing list