Name
Name

Reputation: 156

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!

Upvotes: 3

Views: 281

Answers (2)

Nathan Dorfman
Nathan Dorfman

Reputation: 341

The string "abc" is short enough for short string optimization. See What are the mechanics of short string optimization in libc++?

If you change it to a longer string you will see the same address.

Upvotes: 5

NathanOliver
NathanOliver

Reputation: 180955

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.

Upvotes: 7

Related Questions