为什么添加默认的移动赋值运算符会破坏标准交换函数的编译?

Xev*_*ous 3 c++ raii move-semantics

在以下代码中,如果未注释移动分配,则交换函数将停止程序的编译。我在所有 3 个主要编译器(GCC、Clang、MSVC)上观察到了这种行为。

#include <utility>
#include <memory>

struct test
{
    test() = default;

    test(test&& other) noexcept = default;
    //test& operator=(test&& other) noexcept = default;

    test(const test& other)
    : ptr(std::make_unique<int>(*other.ptr))
    {}

    test& operator=(test other) noexcept
    {
        std::swap(*this, other);
        return *this;
    }

    std::unique_ptr<int> ptr;
};
Run Code Online (Sandbox Code Playgroud)

Godbolt 测试: https: //godbolt.org/z/v1hGzzEaz

研究标准库实现时,他们使用 SFINAE 或概念来启用/禁用std::swap重载,并且当特殊函数未注释时,由于某种原因,某些特征会失败(is_move_constructible和/或is_move_assignable在 libstdc++ 上)。

我的问题是:为什么添加默认的特殊成员函数会阻止标准库将类型视为可移动?

T编辑1:事实证明,问题在于 xvalues 在和之间的重载解析中没有偏好T&&(这会导致不明确的重载错误),因此标准库特征无法将类型识别为可移动。

编辑 2:重要提示:请注意,示例代码不是复制和交换习惯用法的正确实现。应该使用自定义交换函数或使用所有 5 个特殊成员函数来完成。当前的实现创建了移动/复制分配和交换调用的无限递归。

Jan*_*tke 5

主要实现std::swap在内部使用移动分配,如下所示:

template <typename T>
  requires std::is_swappable_v<T> // exposition-only, constraint might be different
void swap(T& a, T& b) {
    T c = std::move(a);
    a = std::move(b);
    b = std::move(c);
}
Run Code Online (Sandbox Code Playgroud)

这意味着移动分配需要对您的类型有效,但事实并非如此。如果你调用移动赋值运算符,你会得到一个错误:

<source>:18:15: error: use of overloaded operator '=' is ambiguous [...]
[...] |
<source>:9:11: note: candidate function
    9 |     test& operator=(test&& other) noexcept = default;
      |           ^
<source>:15:11: note: candidate function
   15 |     test& operator=(test other);
      |           ^
Run Code Online (Sandbox Code Playgroud)

std::swap受到限制,因此只能交换MoveAssignable类型,而您的类型则不能。两个=运算符都可以使用 xvalue 进行调用,但两者都不是更好的匹配。这是因为只有左值到右值的转换会延长转换序列,并且从 xvalue 初始化对象被认为是“免费的”(例如,这不是转换,也不比绑定引用差) 。

即使你可以打电话std::swap,也不能同时打电话

  • 依赖于std::swap使用的默认实现operator=
  • 定义operator=为std::swap

=这将是无限递归,因为和 的定义std::swap是循环的。

解决方案

您可以为您的类型定义自定义swap,这样您就不再依赖std::swap. 只保留operator=(test),它看起来像:

friend void swap(test& a, test& b) noexcept {
    using std::swap;    // Use swap() functions found through ADL, fall back
    swap(a.ptr, b.ptr); // onto std::swap if there are none.
}                       // (not necessary if you only have a std::unique_ptr member,
                        // you could just use std::swap(a.ptr, b.ptr)).

test& operator=(test other) noexcept {
    swap(*this, other); // custom function, not std::swap
    return *this;
}
Run Code Online (Sandbox Code Playgroud)

您还可以单独定义operator=(const test&)并operator=(test&&)手动定义,这样就std::swap可以使用移动赋值运算符,并且重载决策中不会有任何歧义。