首页 > 解决方案 > 隐式移动构造函数

问题描述

隐式移动构造函数到底在做什么?例如,以下类的隐式移动构造函数将如何(您能否提供此隐式构造函数的一些示例实现):

struct A
{
    A()           = default;
    A(A && other) = default;
    int a;
};

struct B : public A
{
    int b;
    int * c;
};

实现会像这样:

B(B && other) : A(std::move(other)), b(std::move(other.b)), c(std::move(other.c)) {}

标签: c++c++11move-semantics

解决方案


来自 cppreference.com:

对于联合类型,隐式定义的移动构造函数复制对象表示(如 std::memmove)。对于非联合类类型(类和结构),移动构造函数使用带有 xvalue 参数的直接初始化,按照 初始化顺序对对象的基类和非静态成员执行完整的成员移动。如果这满足 constexpr 构造函数的要求,则生成的移动构造函数是 constexpr。

基类构造函数在派生构造函数之前运行。


推荐阅读