Which is the correct/safer/efficient way to concatenate strings with a string_view object to produce a string:
std::string_view foo{"foo"};
auto concat = foo.data() + std::to_string(45);
OR
auto concat = std::string(foo) + std::to_string(45);
Not using .data()
results in a compilation error:
no match for ‘operator+’ (operand types are ‘std::string_view’ {aka ‘std::basic_string_view’} and ‘std::string’ {aka ‘std::__cxx11::basic_string’})
18 | auto concat = foo + std::to_string(45);
| ~~~ ^ ~~~~~~~~~~~~~~~~~~
| | |
| | std::string {aka std::__cxx11::basic_string<char>}
| std::string_view {aka std::basic_string_view<char>}
In the first usage that uses data(), I'm mainly concerned about this note from reference that says:
std::basic_string_view::data() returns a pointer to a buffer that is not necessarily null-terminated
But that call seems to work ok. So why would I prefer string constructed out of the string_view object method over passing the data pointer?