首页 > 解决方案 > 为什么我不能从移动复制ctor调用移动分配?

问题描述

如果我可以从移动 ctor 调用移动分配操作,有时它看起来像节省时间。但是当我尝试时,它会直接将我带到常规作业:

#include <iostream>
using namespace std;

class MyClass
{
public:
    MyClass() { }
    MyClass(const MyClass& other) { /* do some stuff */ }
    MyClass(MyClass&&      other);                  //move ctor

    const MyClass& operator= (const MyClass& other);
    const MyClass& operator= (MyClass&&      other); //move =
};

MyClass::MyClass(MyClass&& other)                   //move ctor
{
    cout << "Calling move ctor\n";
    *this = other; //<<--THIS IS THE PROBLEM
}

const MyClass& MyClass::operator= (MyClass&& other) //move =
{
    cout << "Calling move =\n";
    return *this;
}

const MyClass& MyClass::operator= (const MyClass& other)
{
    cout << "Calling standard =\n";
    if (this == &other) return *this;
    return *this;
}

MyClass makeVectorToTestMoveCtor() { MyClass V; return V; }

int main ()
{
    MyClass V = makeVectorToTestMoveCtor();

    return 0;
}

我可以用 std::move 强制它:

    cout << "Calling move ctor\n";
    *this = std::move(other); 

...但如果这不是一个坏主意,我肯定不需要强迫它吗?我应该在这里做什么?

标签: c++17move-semantics

解决方案


施工是更基础的操作。您必须先有一个构造对象,然后才能分配给它或从它分配。用构造的方式写你的作业,而不是相反。


推荐阅读