如果一个类型真正可移动构造,如何获得

Jon*_*ych 5 c++ stl type-traits move-semantics

以此代码为例:

#include <type_traits>
#include <iostream>

struct Foo
{
    Foo() = default;
    Foo(Foo&&) = delete;
    Foo(const Foo&) noexcept
    {
        std::cout << "copy!" << std::endl;
    };
};

struct Bar : Foo {};

static_assert(!std::is_move_constructible_v<Foo>, "Foo shouldn't be move constructible");
// This would error if uncommented
//static_assert(!std::is_move_constructible_v<Bar>, "Bar shouldn't be move constructible");

int main()
{
    Bar bar {};
    Bar barTwo { std::move(bar) };
    // prints "copy!"
}
Run Code Online (Sandbox Code Playgroud)

因为Bar是从Foo派生的,所以它没有移动构造函数.它仍然可以通过使用复制构造函数来构造.我了解了为什么它从另一个答案中选择了复制构造函数:

如果y是类型S,则std::move(y)类型S&&的引用与类型兼容S&.因此S x(std::move(y))完全有效并调用复制构造函数S::S(const S&).

-Lærne,理解std::is_move_constructible

所以我理解为什么rvalue"降级"从移动到左值复制,因此为什么std::is_move_constructible返回true.但是,有没有办法检测类型是否真正可移动构造,不包括复制构造函数?

C.M*_*.M. 10

有人声称无法检测到移动构造函数的存在&&,从表面上看它们似乎是正确的——绑定的方式const&使得无法判断类接口中存在哪些构造函数。

然后我突然想到——C++ 中的移动语义不是一个单独的语义...它是复制语义的“别名”,是类实现者可以“拦截”并提供替代实现的另一个“接口”。所以问题是“我们能检测到移动向量的存在吗?” 可以重新表述为“我们可以检测到两个复制接口的存在吗?”。事实证明,我们可以通过(ab)使用重载来实现这一点——当有两种同样可行的方法来构造对象时,它无法编译,并且可以使用 SFINAE 检测到这一事实。

30行代码胜过一千个字:

#include <type_traits>
#include <utility>
#include <cstdio>

using namespace std;

struct S
{
    ~S();
    //S(S const&){}
    //S(S const&) = delete;
    //S(S&&) {}
    //S(S&&) = delete;
};

template<class P>
struct M
{
    operator P const&();
    operator P&&();
};

constexpr bool has_cctor = is_copy_constructible_v<S>;
constexpr bool has_mctor = is_move_constructible_v<S> && !is_constructible_v<S, M<S>>;

int main()
{
    printf("has_cctor = %d\n", has_cctor);
    printf("has_mctor = %d\n", has_mctor);
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 您可能应该能够将此逻辑与其他const/volatile重载混淆,因此这里可能需要一些额外的工作

  • 怀疑这个魔法是否适用于私有/受保护的构造函数——另一个值得关注的领域

  • 似乎不适用于 MSVC(按照传统)