c++ - 将大字符串作为右值传递时的 std::move 性能?
问题描述
std::move 如何帮助提高性能?我读到它不会复制它会转移所有权,但它是如何发生的?我的主要问题是,如果我们使用 std::move 将大对象或大字符串作为右值传递,它将如何帮助不进行复制,但在复制赋值运算符或复制构造函数中会有一些副本?由于堆栈对象的范围有限,它将如何转移基于堆栈的对象的所有权?
解决方案
一个非常简化的视图std::string
:
namespace std {
class string
{
private:
char *_M_string;
size_t _M_size;
// as you can see, std::string is basically just a wrapper
// around char * and size
public:
// this constructs an empty string
string()
: _M_string(nullptr), _M_size(0) { }
// this will actually copy the string, so it's not interesting to us...
string(const string &other);
// this is the constructor that will be called when you use std::move
string(string &&other)
: string() // <-- construct an empty string first
{
// swap our stuff with "other"s possibly non-empty stuff
swap(_M_string, other._M_string);
swap(_M_size, other._M_size);
// and now "other" string is empty and "this" string has its content
}
~string()
{
// deleting a nullptr is fine
delete [] _M_string;
}
//... other stuff
};
} // std
所以背后没有“魔法” std::move
,它唯一能做的就是帮助选择正确的构造函数重载,然后由类的实现来利用它的内部表示并尽可能地制作一个“便宜的副本”,而使“其他”对象处于某种有效的“空”状态。
推荐阅读
- prolog - Prolog,从图中删除节点
- c - 如何通过管道发送序列化的动态分配结构
- html - Chrome 中的其他 DOM css 淡出出现模糊图像的“白色边框”。如何避免这种情况?
- amazon-web-services - 如何用新的 EB 环境替换弹性 beanstalk 实例?
- python - 在 NLTK CFG 中向用户定义的语法添加单词和规则
- github-actions - 复合 github 动作,自动 cd 进入动作目录?
- python - 如何在 Jupyter Notebook 中获取代码列表?
- mysql - 您可以在 MySQL 工作台中删除“sys”数据库还是必须在那里?
- reactjs - TypeError:主题未定义 - 尝试渲染 Material UI 组件时
- javascript - 登录用户只能看到他自己的内容(Angular+Firebase)