为什么显式调用基本移动构造函数实际上调用基本副本构造函数? [英] Why explicit call of base move constructor actually calls base copy constructor?

查看:103
本文介绍了为什么显式调用基本移动构造函数实际上调用基本副本构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过派生类move ctor显式地调用基类move ctor,但是,惊喜!,实际上调用基类copy ctor而不是基类move ctor。



我在对象上使用 std :: move()函数来确保派生的move ctor被调用



代码:

  class Base 
{
public:
Base(const Base& rhs){cout< base copy ctor<< endl; }
Base(Base&& rhs){cout<< base move ctor<< endl; }
};

class Derived:public Base
{
public:

Derived(Derived& rhs):Base(rhs){cout< ; derived move ctor; }
Derived(const Derived& rhs):Base(rhs){cout< derived copy ctor<< endl; }
};

int main()
{
派生a;
派生y = std :: move(a); // invoke move ctor
cin.ignore();
return 0;
}

计划输出:


基本副本ctor



派生move ctor


正如你所看到的,基类move ctor被遗忘了,那么如何调用呢?

解决方案

Derived 类的上下文中,参数 rhs 显然有一个名称。因此,它必须是一个左值,它不能是一个右值。但是, T&& 只会绑定到右值。如果你想调用基类的move构造函数,你需要使用这样的代码:

  Derived(Derived&& rhs) :Base(std :: move(rhs)){std :: cout< derived move ctor; } 

这将调用 Base的move构造函数并移动 rhs Base 部分。由于 Base 不知道关于 Derived 成员的任何信息, Base move constructor不会移动 Derived 添加的任何内容。


I'm trying to call the base class move ctor explicitly through derived class move ctor but, surprise!, that actually calls the base class copy ctor NOT the base class move ctor.

I'm using std::move() function on an object to be sure that the derived move ctor is being invoked!

The code:

class Base
{
public:
    Base(const Base& rhs){ cout << "base copy ctor" << endl; }
    Base(Base&& rhs){ cout << "base move ctor" << endl; }
};

class Derived : public Base
{
public:

    Derived(Derived&& rhs) : Base(rhs) { cout << "derived move ctor"; }
    Derived(const Derived& rhs) : Base(rhs) { cout << "derived copy ctor" << endl; }
};

int main()
{
    Derived a;
    Derived y = std::move(a); // invoke move ctor
    cin.ignore();
    return 0;
}

PROGRAM OUTPUT:

base copy ctor

derived move ctor

As you see, the base class move ctor is being forgotten, so how do I call it?

解决方案

In the context of your Derived class the parameter rhs clearly has a name. Thus, it must be an lvalue, it can't be an rvalue. However, the T&& only binds to rvalues. If you want to call the base class's move constructor you need to use code like this:

Derived(Derived&& rhs): Base(std::move(rhs)) { std::cout << "derived move ctor"; }

This will call the move constructor of Base and move the Base portion of rhs. Since Base doesn't know anything about the Derived members, the Base move constructor won't move anything added by Derived.

这篇关于为什么显式调用基本移动构造函数实际上调用基本副本构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆