STD ::移动性能,同时将大字符串作为rvalue
std::move performance while passing a big string as rvalue?
std ::移动如何有助于性能?我读到它不会复制它的所有权转让,但是它是如何发生的?我的主要问题是,我们是否使用std :: Move将一个大对象或大字符串作为rvalue传递为rvalue?由于堆栈对象的范围受到限制,它将如何转移基于堆栈的对象的所有权?
这已经在这里回答:移动的好处
std ::移动将执行指针的副本,并将源标记为无效。来源将是无效的状态,并且无法使用。std ::移动不会复制内容,因此对象的大小都没关系。
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
背后没有"魔术",它唯一要做的就是帮助选择正确的构造函数超载,之后取决于班级的实现来利用其内部表示,并制作"便宜的副本"如果可能的话,将"其他"对象留在某个有效的"空"状态中。