考虑以下代码:
#include <iostream>
#define P_(x) std::cout << x << std::endl
class B {
public:
B() { P_("B::B()"); }
B(const B&) { P_("B::B(const B&)"); }
B(B&&) { P_("B::B(B&&)"); }
~B() { P_("B::~B()"); }
B& operator=(const B&) { P_("B::op=(const B&)"); return *this; }
B& operator=(B&& b) { P_("B::op=(B&&)"); return *this; }
};
class Foo {
public:
void setB(const B& b) { mB = b; }
private:
B mB;
};
B genB() {
return B();
}
int main() {
Foo f;
f.setB(genB());
}
假设B
是一个难以复制的构造类型。我想生成一些B
(使用函数genB
)并将其存储在Foo
中。由于genB
返回一个临时结果,我希望使用move构造函数。
然而,当我运行代码时,我得到的输出是:
B::B()
B::B()
B::op=(const B&)
B::~B()
B::~B()
这清楚地表明,两个B被创造和摧毁,但第二个是复制品,而不是第一个的移动。
尽可能使用move构造函数的最佳方法是什么?
- 我需要在某个地方调用std::move()吗
B&
和B&&
需要单独的过载吗- 还有什么是我完全遗漏的吗
您可以重载setB
函数:
class Foo {
public:
void setB(const B& b) { mB = b; }
void setB(B&& b) { mB = std::move(b); }
private:
B mB;
};
或者,您可以使用"按值传递"的方式:
class Foo {
public:
void setB(B b) { mB = std::move(b); }
private:
B mB;
};
这里,参数b
将在可能的情况下被移动构造,或者在其他情况下被复制构造。
第一个B
实例是在创建Foo
实例时创建的实例:
Foo f;
这是因为您的Foo
类有一个名为mB
的B
成员。
第二个B
实例是由genB()
调用创建的实例。
调用赋值运算符是因为您在Foo::setB
函数中执行的赋值:
mB = b;
没有任何地方可以使用复制或移动构造函数。