std::string_view là view không sở hữu (non-owning view) vào một chuỗi ký tự — chỉ là con trỏ + độ dài, không copy.
cpp
void print(std::string_view sv) {
std::cout << sv; // không copy
}
print("hello"); // const char* — không tạo std::string
print(std::string{"world"}); // std::string — không copy
print(large_string.substr(0, 5)); // không tạo substring thậtSo với const std::string&:
const std::string& | std::string_view | |
|---|---|---|
const char* argument | Tạo temporary string | Không tạo |
| Substring | Tạo string mới | Zero-copy |
| Non-null-terminated | Không hỗ trợ | Hỗ trợ |
| Có thể dangle | Không | Có (nếu string gốc bị xóa) |
Dùng khi: hàm chỉ đọc string, không cần null-terminated, không store lại.
Không dùng khi: cần lưu string lâu dài — nguy cơ dangling view.
std::string_view is a non-owning view into a character sequence — just a pointer + length, zero copies.
cpp
void print(std::string_view sv) {
std::cout << sv; // no copy
}
print("hello"); // const char* — no std::string created
print(std::string{"world"}); // std::string — no copy
print(large_string.substr(0, 5)); // no actual substring allocationvs const std::string&:
const std::string& | std::string_view | |
|---|---|---|
const char* argument | Creates temporary string | Does not |
| Substring | Allocates new string | Zero-copy |
| Non-null-terminated | Not supported | Supported |
| Can dangle | No | Yes (if original string is destroyed) |
Use when: function only reads the string, doesn't need null-termination, won't store it.
Don't use when: storing the value long-term — dangling view risk.