提问者:小点点

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


根据这个问题的回答,在一定的条件下,可以将一个默认的移动构造函数定义为no异常。例如,下面的类生成了一个no异常移动构造函数:

class C {};

根据对这个问题的回答,用=默认说明符定义的移动构造函数将生成与隐式定义的移动构造函数相同的构造函数。所以,如果我正确地理解它,下面的类应该生成一个no异常移动构造函数:

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

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

#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

我也试过用叮当声,我得到了同样的错误。以下是有关我的编译器的信息:

$ 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个答案

匿名用户

事实上,它与noexcept无关<代码>静态断言也会失败,因为移动构造函数是私有的。所以只需将其声明为public

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

生活与clang8

匿名用户

我认为问题在于您默认的D的move构造函数是私有的。尽量公开。