From cppreference.com
CharT&operator[](size_typepos); (1)(constexpr since C++20)constCharT&operator[](size_typepos)const; (2)(constexpr since C++20)Returns a reference to the character at specified location pos if pos<size(), or if pos==size():
1)
The behavior is undefined.
(until C++11)Returns a reference to CharT(), if the object referred by the returned reference is modified to any value other than CharT(), the behavior is undefined.
(since C++11)2) Returns a reference to CharT().
If pos>size() is true, the behavior is undefined.
(until C++26)If pos>size() is true:
If the implementation is
, a
occurs.
If the implementation is not hardened, the behavior is undefined.
(since C++26)Parameters
pos - position of the character to return Return value
1)*(begin()+pos) if pos<size(), or a reference to CharT() if pos==size()(since C++11).
2)*(begin()+pos) if pos<size(), or a reference to CharT() if pos==size().
Complexity
Constant.
Example
Run this code
#include<iostream>#include<string>intmain(){conststd::stringe("Exemplar");for(unsignedi=e.length()-1;i!=0;i/=2)std::cout<<e[i];std::cout<<'\n';constchar*c=&e[0];std::cout<<c<<'\n';// print as a C string// Change the last character of s into a 'y'std::strings("Exemplar ");s[s.size()-1]='y';// equivalent to s.back() = 'y';std::cout<<s<<'\n';}Output:
rmx Exemplar Exemplary Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
DR Applied to Behavior as published Correct behavior
C++98 overload (
) could return const lvalue
data()[pos], which was ill-formed changed to return
*(begin()+pos)
C++11 if pos==size(), the behavior of modifying the
object referred by the returned reference was undefined well-defined if
modified to CharT()See also
accesses the specified character with bounds checking
(public member function)
(DR*)
accesses the first character
(public member function)
(DR*)
accesses the last character
(public member function)
accesses the specified character
(public member function of std::basic_string_view<CharT,Traits>)