正在获取要使用的移动构造函数/赋值运算符



考虑以下代码:

#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类有一个名为mBB成员。

第二个B实例是由genB()调用创建的实例。

调用赋值运算符是因为您在Foo::setB函数中执行的赋值:

mB = b;

没有任何地方可以使用复制或移动构造函数。

最新更新