|
Boost : |
From: John Nagle (nagle_at_[hidden])
Date: 2004-06-02 22:45:05
Rob Stewart wrote:
> From: John Nagle <nagle_at_[hidden]>
>
>> I've done some cleanup on my version of fixed_string at
>>
>> http://www.animats.com/source
>>
>>This now conforms to Dunn's decision on length, i.e.
>>
>> "fixed_string<char,4> s" now has space for four characters
>>plus a trailing null.
>
>
> Good.
>
>
>> I decided that "operator[]" had to let users reach the
>>trailing null without a subscript error, so that the classic
>>C idiom of a loop stopped by the trailing null
>>
>> for (i=0; s[i]; i++)
>
>
> Good idea.
>
>
>>would still work. Because "operator[]" can't tell a read from
>>a write, this offers the possibility of overstoring the
>
>
> Sure it can: just return a proxy. Assignment through the proxy
> is a write and can be checked against exceeding N. Conversion of
> the proxy to the character type is a read and can permit
> accessing element N + 1.
Returning a proxy object adds complexity to a very low level
operation, which may not be a good idea. I'm struggling
to keep this rather simple object as simple as possible.
There's also the problem
that the proxy object would have to be on the stack.
Consider
char_string<16> s("0123456789ABCDEF");
char& hexchar(int n)
{ return(s[n]); }
Either we pass back a proxy object by value, which is
expensive, or we pass a reference to a local object,
which is wrong. Or we just pass a char, which
is what people expect. I don't want to get too clever
here.
> Will you still need to reset the trailing null if using the
> proxy?
Some trailing null maintenance is necessary, because
you can mix C++ and C operations. For example;
char_string<72> s = "Hello";
s += '.' // add period
printf("%s\n",s.c_str());
Currently, every use of "operator[]" invalidates the
length.
John Nagle
Team Overbot
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk