相关疑难解决方法(0)

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

以此代码为例:

#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&) …

c++ stl type-traits move-semantics

5
推荐指数
1
解决办法
239
查看次数

标签 统计

c++ ×1

move-semantics ×1

stl ×1

type-traits ×1