gpt4 book ai didi

c++ - 当基类不是时,为什么派生类可以 move 构造?

转载 作者:IT老高 更新时间:2023-10-28 13:23:22 26 4
gpt4 key购买 nike

考虑以下示例:

#include <iostream>
#include <string>
#include <utility>

template <typename Base> struct Foo : public Base {
using Base::Base;
};

struct Bar {
Bar(const Bar&) { }
Bar(Bar&&) = delete;
};

int main() {
std::cout << std::is_move_constructible<Bar>::value << std::endl; // NO
std::cout << std::is_move_constructible<Foo<Bar>>::value << std::endl; // YES. Why?!
}

为什么编译器生成一个 move 构造函数,尽管基类是不可 move 构造的?

这是标准还是编译器错误?是否可以“完美地传播”将构造从基类 move 到派生类?

最佳答案

因为:

A defaulted move constructor that is defined as deleted is ignored by overload resolution.

([class.copy]/11)

Bar的 move 构造函数被明确删除,所以Bar不能 move 。但是Foo<Bar>的 move 构造函数在被隐式声明为默认值后被隐式删除,因为 Bar成员不能 move 。因此Foo<Bar>可以使用其复制构造函数 move 。

编辑:我还忘了提到一个重要的事实,即继承构造函数声明,例如 using Base::Base不继承默认、复制或 move 构造函数,这就是 Foo<Bar> 的原因没有从 Bar 继承的显式删除的 move 构造函数.

关于c++ - 当基类不是时,为什么派生类可以 move 构造?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39139087/

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