GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • cpprefjp - C++日本語リファレンス
  • GitHub Project

This view

  • Original page
  • New address

GeezerVison is showing cpprefjp.github.io — std::basic_string::operator[] - cpprefjp C++日本語リファレンス

  1. リファレンス
  2. string
  3. basic_string
  4. operator[]

最終更新日時: 2026年08月27日 14時02分35秒 (JST)
Akira Takahashi が更新

履歴 編集

function
<string>

std::basic_string::operator[]

const_reference operator[](size_type pos) const;           // (1) C++98
constexpr const_reference operator[](size_type pos) const; // (1) C++20

reference operator[](size_type pos);                       // (2) C++98
constexpr reference operator[](size_type pos);             // (2) C++20

概要

pos 番目の要素への参照を取得する。

堅牢化された事前条件

pos <= size()

戻り値

  • C++98

    • pos < size() の場合、*(begin() + pos) を返す。
    • pos == size() の場合、(1) は charT() の値を持ったオブジェクトへの参照を返す。
    • それ以外の場合は、未定義動作。
  • C++11以降

    • pos < size() の場合、*(begin() + pos) を返す。
    • pos == size() の場合、charT() の値を持ったオブジェクトへの参照を返す。
    • それ以外の場合は、未定義動作。
    • (2) において、pos == size() の場合に返された参照を charT() 以外の値に書き換えた場合の動作は未定義。

例外

投げない

計算量

定数時間

例

#include <iostream>
#include <string>

int main()
{
  std::string s = "hello";
  char& c = s[1];

  std::cout << c << std::endl;
}

出力

e

参照

  • LWG Issue 876. basic_string access operations should give stronger guarantees
    • C++11で、例外を送出しないことと計算量が定数時間であることが規定された
  • LWG Issue 2475. Allow overwriting of std::basic_string terminator with charT() to allow cleaner interoperation with legacy APIs
    • C++17で、非const版(2)のpos == size()で返る参照にcharT()を書き込むことが許可された(レガシーC APIとの相互運用のため)
    • この修正は欠陥報告(DR)であり、C++11以降に遡及して適用される。charT()以外の値を書き込んだ場合の未定義動作は維持されており、処理系はヌル終端文字を実際に保持しているためcharT()の書き込みは当初から問題なく動作していた。要件の緩和であり、既存プログラムの意味は変わらないため
  • P0980R1 Making std::string constexpr
  • P3471R4 Standard library hardening
  • P3878R1 Standard library hardening should not use the 'observe' semantic
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.