Pie*_*rre 28 c++ move-constructor noexcept c++11
根据this question的答案,可以noexcept在某些条件下定义默认移动构造函数。例如,下面的类生成一个noexcept移动构造函数:
class C {};
Run Code Online (Sandbox Code Playgroud)
根据对这个问题的回答,使用说明= default符定义的移动构造函数将生成与隐式定义的移动构造函数相同的构造函数。所以,如果我正确理解它,下面的类应该生成一个noexcept移动构造函数:
class D {
D(D&&) = default;
};
Run Code Online (Sandbox Code Playgroud)
要检查,我使用的std::is_nothrow_move_constructible功能,看是否C和D有一个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;
}
Run Code Online (Sandbox Code Playgroud)
当我编译时,我收到此错误:
$ 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");
^~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)
为什么我的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
Run Code Online (Sandbox Code Playgroud)
son*_*yao 33
事实上,它与noexcept; static_assert也会失败,std::is_move_constructible因为移动构造函数是private. 所以只需将其声明为public.
class D {
public:
D(D&&) = default;
};
Run Code Online (Sandbox Code Playgroud)