【问题标题】:Why is my defaulted move constructor not noexcept?为什么我的默认移动构造函数不是 noexcept?
【发布时间】:2020-05-08 09:13:48
【问题描述】:

根据this question的回答,在一定条件下可以定义一个默认的move构造函数为noexcept。例如,下面的类生成一个noexcept 移动构造函数:

class C {};

根据this question 的答案,使用= default 说明符定义的移动构造函数将生成与隐式定义的移动构造函数相同的构造函数。所以,如果我理解正确的话,下面的类应该会生成一个noexcept 移动构造函数:

class D {
    D(D&&) = default;
};

为了检查这一点,我使用了std::is_nothrow_move_constructible 函数来查看CD 是否有noexcept 移动构造函数:

#include <type_traits>

int main() {
    static_assert(std::is_nothrow_move_constructible<C>::value, "C should be noexcept MoveConstructible");
    static_assert(std::is_nothrow_move_constructible<D>::value, "D should be noexcept MoveConstructible");

    return 0;
}

当我编译时,我得到这个错误:

$ g++ toy.cpp -o toy
toy.cpp: In function ‘int main()’:
toy.cpp:16:5: error: static assertion failed: D should be noexcept MoveConstructible
     static_assert(std::is_nothrow_move_constructible<D>::value, "D should be noexcept MoveConstructible");
     ^~~~~~~~~~~~~

为什么我的D 移动构造函数不是noexcept


我也尝试过使用 Clang,但我得到了同样的错误。以下是关于我的编译器的信息:

$ g++ --version
g++ (Debian 6.3.0-18+deb9u1) 6.3.0 20170516
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$ clang++8 --version
clang version 8.0.0 
Target: x86_64-unknown-linux-gnu
Thread model: posix

【问题讨论】:

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


    【解决方案1】:

    其实和noexcept无关; static_assert 也会与 std::is_move_constructible 一起失败,因为移动构造函数是 private。因此,只需将其声明为 public

    class D {
    public:
        D(D&&) = default;
    };
    

    LIVE with Clang8

    【讨论】:

      【解决方案2】:

      我认为问题在于您默认的 D 的移动构造函数是 private。尝试使其公开

      【讨论】:

        猜你喜欢
        • 2021-04-07
        • 2015-04-24
        • 2019-12-09
        • 1970-01-01
        • 2013-09-10
        • 2022-01-09
        • 2017-01-10
        • 2011-06-16
        • 1970-01-01
        相关资源
        最近更新 更多