首页 > 解决方案 > 将大字符串作为右值传递时的 std::move 性能?

问题描述

std::move 如何帮助提高性能?我读到它不会复制它会转移所有权,但它是如何发生的?我的主要问题是,如果我们使用 std::move 将大对象或大字符串作为右值传递,它将如何帮助不进行复制,但在复制赋值运算符或复制构造函数中会有一些副本?由于堆栈对象的范围有限,它将如何转移基于堆栈的对象的所有权?

标签: c++c++11c++14

解决方案


一个非常简化的视图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,它唯一能做的就是帮助选择正确的构造函数重载,然后由类的实现来利用它的内部表示并尽可能地制作一个“便宜的副本”,而使“其他”对象处于某种有效的“空”状态。


推荐阅读