c++ - 继承后重新获得 move 可构造性

标签 c++ inheritance move move-constructor

考虑以下片段:

#include <iostream>
#include <type_traits>

class base
{
public:

    base(const base &) = default;
    base(base &&) = delete;
};

class daughter : public base
{
};

int main()
{
    std :: cout << std :: is_move_constructible <daughter> :: value << std :: endl;
}

我整个早上都在盯着它看,但我就是想不通它为什么会输出:

1

base 明确不可 move 构造(is_move_constructiblebase 上实际上是 false),并且 daughter 继承自它。为什么它会神奇地再次变得可 move ? daughter 的默认 move 构造函数会是什么样子?

最佳答案

Class base is explicitly not move constructible

但确实如此。该类型特征仅检查 daughter d2( std::move(d1) ); 对于任何两个对象都是良构的。您可能已经在 base 中显式删除了 move c'tor,但在 daughter 中它只是隐式删除了。因此重载决议将正确地选择复制 c'tor。

[over.match.funcs]

8 A defaulted move constructor or assignment operator ([class.copy]) that is defined as deleted is excluded from the set of candidate functions in all contexts.

如果您真的希望daughter 是不可 move 的,您需要显式删除daughter 本身的 move 构造函数。然后重载决议将命中一个显式删除的函数,这将使被检查的构造格式错误。

关于c++ - 继承后重新获得 move 可构造性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53079444/

相关文章:

c++ - 在 lambda 上使用条件运算符调用 std::any_of 会产生意想不到的结果

c++ - 在另一个函数中使用 std::bind 返回对象和占位符作为参数

派生类中非虚函数的 C++ 同名与 `final` 说明符冲突

NodeJS 中的 JavaScript OOP : how?

c++ - 构建字符串 vector 时是否有拷贝?

c++ - Qt Creator 使用位于另一个地方的另一个 GCC 版本

inheritance - Entity Framework 和继承过滤器

c++ - 当 "moved"对象在 union 中有一个 "non-trivial"成员时,为什么要强制复制构造函数?

python - 通过预先应用的参数 move 多个文件

C++:错误:数组下标的无效类型 ‘size_t {aka long unsigned int}[size_t {aka long unsigned int}]’