以此代码为例:
#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&) …