gpt4 book ai didi

c++ - 为什么显式调用基本移动构造函数实际上调用基本复制构造函数?

转载 作者:太空狗 更新时间:2023-10-29 20:06:13 28 4
gpt4 key购买 nike

<分区>

我试图通过派生类 move ctor 显式调用基类 move ctor,但是,惊喜!,它实际上调用基类复制 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()
{
Derived a;
Derived y = std::move(a); // invoke move ctor
cin.ignore();
return 0;
}

程序输出:

base copy ctor

derived move ctor

如您所见,基类 move ctor 被遗忘了,那么我该如何调用它呢?

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com