3 ms·
Are you familiar with C++? That example is roughly equivalent to: #include <string> #include <iostream> #include <string_view> int main() {
by umanwizard 7y ago
Are you familiar with C++? That example is roughly equivalent to:
#include <string>
#include <iostream>
#include <string_view>
int main()
{
std::string name { "Vivian" };
auto nickname = std::string_view { name }.substr(0, 3);
name.clear();
std::cout << "Hello there, " << nickname << "!\n";
}
which will happily compile, but whose behavior is undefined.
- gramakri 7y agoIs the behavior undefined because std::string makes a deep copy of the string? I thought 'Vivian' would be placed in read-only memory and as long as you don't modify it, you can hold read-only references to it.
- umanwizard 7y agoYes, `std::string` owns its own copy of the string in typical implementations (as does Rust's `String` type). `std::string_view` references that copy. `std::string::clear` destroys it, leaving the `std::string_view` dangling.