Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why move() of string changes underlying data position in memory?

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!

like image 284
Name Avatar asked Sep 15 '26 04:09

Name


1 Answers

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.

like image 116
NathanOliver Avatar answered Sep 16 '26 19:09

NathanOliver