当在同一行初始化时,std :: move是调用复制构造函数而不是移动构造函数吗?

时间:2018-03-18 04:06:29

标签: c++11

下面是Foo类,我为其创建了一个复制构造函数,复制赋值运算符和一个移动构造函数。

class Foo
{
public:
Foo() = default;

Foo(Foo const& other)   //copy ctor
{
    if (other.i != nullptr)
        i = new int(*other.i);
}

Foo& operator=(Foo const& other)  //assignment operator
{
    if (other.i != nullptr)
        i = new int(*other.i);
    return *this;
}

Foo& operator=(Foo&& other)  //move ctor. I'm not sure whether this can                           //be used as a move ctor
{
    if (other.i != nullptr)
    {
        i = other.i;
        other.i = nullptr;
    }

    return *this;
}

~Foo()
{
    if (i != nullptr)
    {
        delete i;
        i = nullptr;
    }
}

int *i = nullptr;
};

当我写下代码时,

Foo f2;
f2.i = new int(43);
Foo f1 = std::move(f2);

它调用复制构造函数而不是移动构造函数。 但是当我写下面的时候,

Foo f2;
f2.i = new int(43);
Foo f1;
f1 = std::move(f2);

它调用我定义的移动构造函数。任何人都可以解释为什么会这样吗?

1 个答案:

答案 0 :(得分:1)

您提供了移动分配,但未提供移动构造函数。当我添加一个(下面)时,我按预期使用移动操作。

Foo(Foo && other) noexcept
{
    std::cout << "Move ctor\n";
    i = other.i;
    other.i = nullptr;
}

注意使用noexcept;您也可以将它添加到移动赋值运算符中。

相关问题