首页 > 解决方案 > 为什么字符串的 move() 会改变内存中的底层数据位置?

问题描述

我试图通过 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;
}

输出:

a_str data pointer: 0x63fdf0
b_str data pointer: 0x63fdc0
a_sv:  bc

感谢您的回复!

标签: c++c++17move-semantics

解决方案


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


推荐阅读