개요
- 문자열을 소유하지 않고 읽기만 하는 클래스
- 문자열 포인터와 크기만을 가짐
- 두개의 오버로딩 함수(const char*, const string&)를 만들어야하는 문제 해결
- string을 const char* 인자로 받으면 string 기능을 사용할 수 없고 길이 계산이 필요
- const char*를 const string& 인자로 받으면 임시 객체가 생성되므로 불필요한 메모리를 할당
- 문자열을 소유하고 있지 않으므로 원본의 라이프사이클을 주의해야 함
- substr의 경우 문자열을 새로 생성하므로 O(n)으로 수행되지만 string_view는 또 다른 string_view를 생성하므로 O(1)로 수행
- 멤버 함수
- operations
- starts_with()
- C++20
- view가 주어진 접두사로 시작하는지 여부 반환
- ends_with()
- C++20
- view가 주어진 접미사로 끝나는지 여부 반환
예제
- 코드
#include <iostream>
#include <string>
#include <string_view>
using namespace std;
int main() {
auto overloading = []() {
auto f = [](string_view s) { cout << s << endl; };
f(string("abc"));
f("abc");
};
overloading();
cout << endl << "------" << endl << endl;
auto operations = []() {
string_view sv = "abc";
cout << sv.starts_with("ab") << endl;
cout << sv.starts_with("b") << endl;
cout << sv.ends_with("bc") << endl;
cout << sv.starts_with("b") << endl;
};
operations();
return 0;
}
- 실행 결과