- string[meta header]
- std[meta namespace]
- basic_string[meta class]
- function[meta id-type]
const_reference operator[](size_type pos) const; // (1) C++03
constexpr const_reference operator[](size_type pos) const; // (1) C++20
reference operator[](size_type pos); // (2) C++03
constexpr reference operator[](size_type pos); // (2) C++20pos 番目の要素への参照を取得する。
pos <= size()
-
C++03
-
C++11以降
投げない
定数時間
#include <iostream>
#include <string>
int main()
{
std::string s = "hello";
char& c = s[1];
std::cout << c << std::endl;
}- s[1][color ff0000]
e
- LWG Issue 2475. Allow overwriting of
std::basic_stringterminator withcharT()to allow cleaner interoperation with legacy APIs- C++17で、非const版(2)の
pos == size()で返る参照にcharT()を書き込むことが許可された(レガシーC APIとの相互運用のため) - この修正は欠陥報告(DR)であり、C++11以降に遡及して適用される。
charT()以外の値を書き込んだ場合の未定義動作は維持されており、処理系はヌル終端文字を実際に保持しているためcharT()の書き込みは当初から問題なく動作していた。要件の緩和であり、既存プログラムの意味は変わらないため
- C++17で、非const版(2)の
- P0980R1 Making
std::stringconstexpr - P3471R4 Standard library hardening
- P3878R1 Standard library hardening should not use the 'observe' semantic