Boost logo

Boost :

From: Rob Stewart (stewart_at_[hidden])
Date: 2004-06-03 11:12:29


From: John Nagle <nagle_at_[hidden]>
> Rob Stewart wrote:
> > From: John Nagle <nagle_at_[hidden]>
> >
> >>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.

The complexity is in the implementation, not the use. There also
doesn't have to be much, if any, overhead.

> 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.

Do we really want to allow for such things? I'm not sure a
function like hexchar() is a good idea in any application.
That's not to say that it doesn't occur, but should we preclude
efficiency or safety to permit such code?

> > 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.

I'm apparently missing something. In the above example,
construction will ensure that no more than 72 characters are
copied to the internal buffer and that there is a trailing null.
In the += operator, you'll check to see whether there's room for
another character (within the allotted 72), and will add the
character plus null. Finally, calling c_str() returns const
access to the internal buffer.

Calling operator [] is ranged checked, so you can't exceed 72 or
73. With the proxy approach, you can ensure that no write is
permitted if the index is 73, so there is no need to reset the
null.

In summary, any mutating operation, except operator [], writes
the null, so a proxy returning operator [] only needs to prevent
writes to character N + 1.

-- 
Rob Stewart                           stewart_at_[hidden]
Software Engineer                     http://www.sig.com
Susquehanna International Group, LLP  using std::disclaimer;

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk