std::string vs. std::stringview — when is stringview dangerous?
C++Level: IntermediateStrings
std::string vs. std::string_view — when is string_view dangerous?
Hints
- Identify types, object lifetimes and compile-time decisions.
- Separate language guarantees from a particular compiler's behavior.
Answer
std::string_view
:Source: src/string/string-view
Introduced in C++17, std::string_view provides a non-owning reference to
a character sequence. It avoids copying when you only need to read string data,
making it ideal for function parameters that don't need ownership. However,
care must be taken to ensure the underlying data outlives the view.
Accepting string_view parameters:
Functions that only read string data should prefer std::string_view
parameters. This accepts both std::string and C strings without copying:
#include <iostream>
#include <string_view>
void print(std::string_view s) {
std::cout << s << "\n";
}
int main(int argc, char *argv[]) {
const std::string s = "foo";
print(s); // Works: string converts to string_view
print("bar"); // Works: C string converts to string_view
}
Converting string_view to string:
A std::string_view cannot implicitly convert to std::string because
this would involve a potentially expensive copy. Explicit conversion is
required to make the cost visible:
#include <iostream>
#include <string>
#include <string_view>
void process(std::string s) {
std::cout << s << "\n";
}
int main(int argc, char *argv[]) {
std::string_view sv = "foo";
// process(sv); // Error: no implicit conversion
process(std::string(sv)); // OK: explicit conversion
}
Null-termination caveat:
Unlike std::string, a std::string_view is not guaranteed to be
null-terminated. This is important when interfacing with C APIs that expect
null-terminated strings. The data() member function returns a pointer
to the underlying character array, but there may be no null terminator:
#include <cstring>
#include <iostream>
#include <string_view>
int main(int argc, char *argv[]) {
char array[3] = {'B', 'a', 'r'}; // No null terminator
std::string_view sv(array, sizeof(array));
// Safe: use size() to limit iteration
for (size_t i = 0; i < sv.size(); ++i) {
std::cout << sv[i];
}
std::cout << "\n";
// Dangerous: strlen expects null-terminated string
// std::cout << std::strlen(sv.data()) << "\n"; // Undefined behavior
}
note:
When passing std::string_view to C APIs, first convert to
std::string to ensure null-termination, or verify the view
was created from a null-terminated source.
Source and licence: C/C++ Interview Cheatsheet — Chang Ning Tsai · MIT