简体   繁体   English

C++ - 为包含字符串的类移动构造函数

[英]C++ - Move constructor for class containing strings

class Foo { int a; int b; int c; std::wstring d; std::vector<char*> e };

Assuming a large string (~512 bytes) and ~512 bytes for the std::vector and it's use case as the following:假设std::vector有一个大字符串(~512 字节)和~512 字节,它的用例如下:

void Test()
{
    Foo foo;
    DoSomething(std::move(foo)); // DoSomething will stuff it in a long-lived queue
}

Essentially I want the RAII's object's lifetime to change.基本上我希望 RAII 对象的生命周期发生变化。

Is this when I implement a move constructor and assignment operator?这是在我实现移动构造函数和赋值运算符时吗? Or just doing std::move(..) is good enough?或者只是做std::move(..)就足够了?

std::move is useless without move constructor and/or move assignment operator.如果没有移动构造函数和/或移动赋值运算符, std::move是无用的。

However all members of your class are movable and you don't have any user-defined destructor, copy constructor or copy assigment operator, so there will be an implicitly defined move constructor and move assignment operator doing the correct thing.但是,您的类的所有成员都是可移动的,并且您没有任何用户定义的析构函数、复制构造函数或复制赋值运算符,因此将有一个隐式定义的移动构造函数和移动赋值运算符做正确的事情。

So in this specific case the answer is that you don't need to define a move constructor or assignment operator.因此,在这种特定情况下,答案是您不需要定义移动构造函数或赋值运算符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM