I have read some questions and documentation, and I guess answer is yes, since string_view will never touch the pointed to stuff, but I am a still bit confused if this is legal:
std::vector<char> v;
std::string_view sv(v.data(), v.size());
note:
- I know that constructor that just uses
v.data()and doesstrlenwill crash, I am asking about this particular way of constructingstd::string_view. - I know that constructed
string_viewis "evil", e.g. doingstd::cout << sv.data()is UB, but I thinkstd::cout << sv;should work
Full example:
#include <vector>
#include <iostream>
#include <string_view>
std::vector<char> v;
auto get_sv() {
std::string_view sv(v.data(), v.size());
return sv;
}
int main() {
std::cout << "|" << get_sv() << "|" << std::endl;
}