views:

163

answers:

2

This question has no practical issues associated with it, it is more a matter of curiosity and wanting to know if I am taking things too literally ;).

So I have been trying to work towards understanding as much of the c++ standard as possible. Today in my delving into the standard I noticed this (ISO/IEC 14882:2003 21.3.4):

const_reference operator[](size_type pos) const;
reference operator[](size_type pos);
Returns: If pos < size(), returns data()[pos].
         Otherwise, if pos == size(), the const version returns charT().
         Otherwise, the behavior is undefined.

Seems pretty sane to me. But then I thought to myself, wait a sec what's the definition of data()?.

const charT* data() const;

yup, it returns a const charT*.

Clearly the non-const version of operator[] cannot be implemented as a simple return data()[pos] then since that would be initializing a reference of type char& from an expression of type const char.

I think that it is obvious that the intent is that data() be implemented something like return data_; and operator[] be implemented as return data_[pos]; or something functionally similar, but that's not what the standard says :-P.

If I recall correctly, implementors have some leeway in that they can implement things how they please as long as it meets the basic requirements given and has the same net effect.

So the question is, am I being way too literal, or is this the type of thing that would be considered a defect.

EDIT: It is worth noting that the c++0x draft has changed the wording to:

Returns: If pos < size(), returns *(begin() + pos).
         Otherwise, if pos == size(), the const version returns charT().
         Otherwise, the behavior is undefined.

So perhaps I have just stumbled onto something that has already been discussed.

+1  A: 

I assume that they used data() in the definition instead of data_ becuase they wanted to define in strictly in terms of the public interface.

James Curran
@James Curran: sure, but it literally **won't compile** if the non-const version of `operator[]` is implemented as `return data()[pos];`
Evan Teran
@Evan: Unfortunately, they forgot to compile the standard before publishing it.
Mike Seymour
@Mike: Stack Overflow detected: you'd need a standard-compliant compiler for that, which requires a standard, which requires a standard-compliant compiler, which ....
MSalters
+5  A: 

Yes, it was a defect and yes, this was the fix.

http://www.open-std.org/JTC1/SC22/WG21/docs/lwg-defects.html#259

Charles Bailey