I'm trying to save some string via string_view to second data container but run into some difficulties. It turns out that string changes its underlying data storage after move()'ing it.
And my question is, why does it happen?
Example:
#include <iostream>
#include <string>
#include <string_view>
using namespace std;
int main() {
string a_str = "abc";
cout << "a_str data pointer: " << (void *) a_str.data() << endl;
string_view a_sv = a_str;
string b_str = move(a_str);
cout << "b_str data pointer: " << (void *) b_str.data() << endl;
cout << "a_sv: " << a_sv << endl;
}
Output:
a_str data pointer: 0x63fdf0
b_str data pointer: 0x63fdc0
a_sv: bc
Thanks for your replies!
What you are seeing is a consequence of short string optimization. In the most basic sense, there is an array in the string object to save a call to new for small strings. Since the array is a member of the class, it has to have it's own address in each object and when you move a string that is in the array, a copy happens.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With