【问题标题】:Calling of move constructor in c++在 C++ 中调用移动构造函数
【发布时间】:2017-11-01 06:14:47
【问题描述】:

我有以下代码:

struct Base
{
    std::vector<int> a;
}

struct Derived : public Base
{
    Derived(Base && rhs):
        Base( std::forward<Base>(rhs))
    {
    }
    //some more fields
}
//...
Base a;
Derived b(std::move(a));

调用Derived 构造函数会导致调用std::vector 包含在Base 类中的移动构造函数吗?

【问题讨论】:

  • 是的,Base partDerived object 的构造过程将调用 Base 的隐式定义的 move c'tor,这将调用 Base 的所有数据成员的 move 构造函数。
  • 你应该在这里使用 std::move 。 std::forward 用于转发传递给模板函数的参数。

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


【解决方案1】:

是的,Baseimplicitly-defined move constructor 被调用,它将对其数据成员 a 执行移动。

对于非联合类类型(类和结构),移动构造函数使用带有 xvalue 参数的直接初始化,按照初始化顺序对对象的基类和非静态成员执行完整的成员移动。

LIVE for confirming

【讨论】:

    猜你喜欢
    • 2011-05-22
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 2021-08-06
    • 1970-01-01
    • 2012-10-17
    相关资源
    最近更新 更多