basic_string_view — std::basic_string_view

basic_string_view — std::basic_string_view

std::basic_string_view 클래스 템플릿은 첫 번째 원소가 0번 위치인, CharT의 연속된 상수 시퀀스를 참조할 수 있는 객체를 나타내요. C++17에서 도입됐어요. <string_view> 헤더에 있어요.

문자열을 소유하지 않고 관찰하는 비소유(non-owning) 뷰예요.

출처: cppreference

본문

// <string_view> 헤더, C++17
template<
    class CharT,
    class Traits = std::char_traits<CharT>
> class basic_string_view;

basic_string_view str에 대해, 포인터 pstr.data()이고 시작 위치 0의 시퀀스를 가리켜요.

타입 별칭

별칭 타입
std::string_view basic_string_view<char>
std::wstring_view basic_string_view<wchar_t>
std::u8string_view UTF-8/16/32

사용 예

#include <string_view>
#include <iostream>

void print(std::string_view sv) {   // 복사하지 않고 관찰
    std::cout << sv << '\n';
}

std::string s = "hello";
print(s);                     // std::string에서 변환 (복사 없음)
print("world");               // 리터럴
print(std::string_view(s).substr(0, 2));  // "he"

소유하지 않는 특성

std::string s = "abcdef";
std::string_view sv = s;        // s를 참조 (소유 안 함)
sv.remove_prefix(2);            // "cdef" (뷰만 이동)
sv.remove_suffix(1);            // "cde"
// s는 그대로

주요 연산

  • 관찰data(), size(), length(), empty(), operator[], front(), back()
  • 변형(뷰)substr(), remove_prefix(), remove_suffix()
  • 검색find(), rfind(), find_first_of(), starts_with(), ends_with()
  • 비교compare(), ==, <
  • 변환std::string으로 생성·복사
std::string_view sv = "hello world";
sv.starts_with("hello");   // true
sv.ends_with("world");     // true
auto sub = sv.substr(6);   // "world"

주의

  • 문자열 뷰는 **참조하는 문자열이 사라지면 댕글링(dangling)**이 돼요. 수명에 주의.
  • 복사·할당이 없는 비소유 형태라 성능에 유리해요.
// 수명 주의: 문자열을 반환하면 안 됨
std::string_view bad() {
    std::string local = "temp";
    return local;   // local 파괴 → 댕글링 UB
}

std::string_view는 소유 없이 문자열의 일부를 읽고 전달하는 현대 C++의 표준 방식이에요. 함수 인자로 관찰만 할 때 이상적이에요.

더 알아보기 (Learn more)

cppreference