为什么字符串的 move() 会改变内存中的底层数据位置?

Nam*_*ame 2 c++ move-semantics c++17

我试图通过 string_view 将一些字符串保存到第二个数据容器,但遇到了一些困难。事实证明,字符串在 move() 之后改变了它的底层数据存储。

我的问题是,为什么会发生这种情况?

例子:

#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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

a_str data pointer: 0x63fdf0
b_str data pointer: 0x63fdc0
a_sv:  bc
Run Code Online (Sandbox Code Playgroud)

感谢您的回复!

Nat*_*ica 5

您所看到的是短字符串优化的结果。在最基本的意义上,字符串对象中有一个数组,用于保存对小字符串的 new 调用。由于数组是类的成员,因此它必须在每个对象中拥有自己的地址,并且当您移动数组中的字符串时,就会发生复制。


小智 5

字符串“abc”对于短字符串优化来说足够短。请参阅libc++ 中短字符串优化的机制是什么?

如果将其更改为更长的字符串,您将看到相同的地址。