constexpr basic_string_view<charT, traits>
subview(size_type pos = 0,
size_type n = npos) const;
概要
部分文字列のstd::basic_string_viewを構築する。
pos番目からn要素のstd::basic_string_viewを返す。
引数省略時は、先頭位置(0番目)から全要素(npos)の文字列を返す。
要件
pos <= size()
効果
次と等価 : return basic_string_view<charT, traits>(*this).subview(pos, n)。
注意
本関数は使い方を誤ると、ぶら下がり参照が発生し得る。
#include <print>
#include <string>
#include <string_view>
int main() {
// OK
std::string s(3, 'A');
std::string_view sv = s.subview();
std::println("{}", sv);
// OK
std::println("{}", std::string(3, 'A').subview());
// NG!
std::string_view d = std::string(3, 'A').subview(); // ぶら下がり参照発生
std::println("{}", d); // 不定動作
}
例
#include <iostream>
#include <string>
#include <string_view>
int main() {
std::string s = "Hello world!";
std::string_view sv = s.subview(6, 5);
std::cout << sv;
}
出力
world
バージョン
言語
- C++26
処理系
- Clang: ??
- GCC: ??
- ICC: ??
- Visual C++: ??