std::basic_string<CharT,Traits,Allocator>::operator[]

Returns a reference to the character at specified location pos if pos < size(), or a reference to CharT() if pos == size(). No bounds checking is performed.

# Declarations

CharT& operator[]( size_type pos );

(constexpr since C++20)

const CharT& operator[]( size_type pos ) const;

(constexpr since C++20)

# Parameters

# Return value

Reference to the requested element if pos < size(), or a reference to CharT() if pos == size().

# Example

#include <iostream>
#include <string>
 
int main()
{
    const std::string e("Exemplar");
    for (unsigned i = e.length() - 1; i != 0; i /= 2)
        std::cout << e[i];
    std::cout << '\n';
 
    const char* c = &e[0];
    std::cout << c << '\n'; // print as a C string
 
    // Change the last character of s into a 'y'
    std::string s("Exemplar ");
    s[s.size() - 1] = 'y'; // equivalent to s.back() = 'y';
    std::cout << s << '\n';
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 259C++98non-const overload could return const lvalue data()[pos], which was ill-formedchanged to return*(begin() + pos)
LWG 2475C++11if pos == size(), the behavior of modifying theobject referred by the returned reference was undefinedwell-defined ifmodified to CharT()

# See also