You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@stdcxx.apache.org by Anton Pevtsov <An...@moscow.vdiweb.com> on 2006/05/04 16:12:37 UTC

test for lib.string.access

I am porting the test for lib.string.access methods (operator[] and at)
and found one issue.

The code 

#include <string>

int main (void)
{
    std::string s ("a", 1);
    const char& c = s[1];

    return 0;
}

results in assertion and fails. But the standard says for 
const_reference operator[] (size_type pos) const:

"If pos < size() returns data()[pos]. Otherwise, if pos == size(), the
const version returns charT(). Otherwise, the behavior is undefined."

So I expect charT() without any asserts.

What do you think about this?


Thanks,
Anton Pevtsov.

Re: test for lib.string.access

Posted by Martin Sebor <se...@roguewave.com>.
Anton Pevtsov wrote:
> I am porting the test for lib.string.access methods (operator[] and at)
> and found one issue.
> 
> The code 
> 
> #include <string>
> 
> int main (void)
> {
>     std::string s ("a", 1);
>     const char& c = s[1];
> 
>     return 0;
> }
> 
> results in assertion and fails. But the standard says for 
> const_reference operator[] (size_type pos) const:

But that's not the function that gets called in the test. The
string object is not const so the non-const overload of the
operator is invoked.

To invoke the const overload on a non-const object a cast is
necessary:

     const char& c = const_cast<const std::string&>(s)[1];

Martin