为什么我的默认移动构造函数不是noexcept?

28

根据这个问题的回答,当满足一定条件时,默认移动构造函数可以定义为noexcept。例如,以下类会生成一个noexcept移动构造函数:

class C {};
根据对 此问题 的回答,使用 = 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
2个回答

33

实际上这与noexcept无关;static_assert也会在std::is_move_constructible中失败,因为移动构造函数是private的。所以只需将其声明为public

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

使用Clang8进行直播


13

我认为问题在于您将D的移动构造函数默认设置为私有。尝试将其改为公开


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接