问题描述
考虑以下类别,实现移动构造函数的正确方法是:
class C {
public:
C();
C(C& c);
private:
std :: string string;
}
当然,想法是避免复制 string
或重新分配它两次。
假设基本示例只是为了清楚起见,我需要一个移动构造函数。
holar我试过:
C :: C(C& C){
// move ctor
string = std :: move(c.string);
}
和
C :: C(C& c):string(std :: move(c.string)){
// move ctor
}
在gcc 4.8上编译并运行良好。这似乎选项A是正确的行为, string
被复制,而不是移动选项B.Æ
这是 std :: string
正确实现移动构造函数
它本身有一个move-ctor, C
的隐式定义的move-ctor将负责正确的移动操作。你不能自己定义它。但是,如果您有任何其他数据成员,并且具体:
您可能想实现自己的move-ctor。
在需要move-ctor的情况下,更喜欢初始化列表语法。总是!否则,你可能会得到一个默认的构造,每个对象在初始化器列表中没有提到(这是你只能为非默认ctors的成员对象)。
What would be the correct way to implement a move constructor considering the following class:
class C {
public:
C();
C(C&& c);
private:
std::string string;
}
Of course, the idea is to avoid copying string
or deallocating it twice.
Lets assume the basic example is just for clarity and I do need a move constructor.
I tried:
C::C(C&& c) {
//move ctor
string = std::move(c.string);
}
And
C::C(C&& c) : string(std::move(c.string)) {
//move ctor
}
Both compile fine on gcc 4.8 and run fine. It seems option A is the correct behaviour, string
gets copied instead of moved with option B.
Is this the correct implementation of a move constructor?
Since std::string
itself has a move-ctor, the implicitly defined move-ctor for C
will take care of the proper move operation. You may not define it yourself. However, if you have any other data member and specifically:
you may want to implement your own move-ctor.
In case you need the move-ctor, prefer the initializer list syntax. Always! Otherwise, you may end up with a default construction per object not mentioned in the initializer list (which is what you're forced for member objects with non-default ctors only).
这篇关于C ++ 11移动构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!