c++ - 为什么字符串的 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
感谢您的回复!
解决方案
您所看到的是短字符串优化的结果。在最基本的意义上,字符串对象中有一个数组来保存对小字符串的 new 调用。由于数组是类的成员,它必须在每个对象中都有自己的地址,并且当您移动数组中的字符串时,会发生副本。
推荐阅读
- javascript - React Native - 同步运行函数
- excel - 如何使用结构化引用进行数组公式?
- python - 使用约束库的跨世界解谜器
- react-native - 如果应用程序关闭,则不会调用 OneSignal onOpened
- python - 从 Python 中的命令行参数获取输入路径和文件、输出路径和文件
- angular - angular7 路由保护和同步 http 订阅
- python - 替换“?”时出错 Python中数据框中的平均值
- postgresql-9.2 - postgres sql:错误:“偏移”处或附近的语法错误
- python - 如何使用 Pandas 更改日期时间格式
- angular - IntelliJ 自动替换双引号字符串