我读过可构造性,并了解到我们可以使用这个函数来检查复制构造函数是否抛出。我写了一些演示如下:
#include <iostream>
struct A { };
struct B { B(const B&){} };
struct C { C(const C&) noexcept {} };
struct D { int a;};
struct E { std::string a;};
struct F { F(const F&)= default; };
struct G { std::string a; G(const G&)= default; };
int main() {
std::cout << std::boolalpha;
std::cout << "is_nothrow_copy_constructible:" << std::endl;
std::cout << "int: " << std::is_nothrow_copy_constructible<int>::value << std::endl;
std::cout << "A: " << std::is_nothrow_copy_constructible<A>::value << std::endl;
std::cout << "B: " << std::is_nothrow_copy_constructible<B>::value << std::endl;
std::cout << "C: " << std::is_nothrow_copy_constructible<C>::value << std::endl;
std::cout << "D: " << std::is_nothrow_copy_constructible<D>::value << std::endl;
std::cout << "E: " << std::is_nothrow_copy_constructible<E>::value << std::endl;
std::cout << "F: " << std::is_nothrow_copy_constructible<F>::value << std::endl;
std::cout << "G: " << std::is_nothrow_copy_constructible<G>::value << std::endl;
return 0;
}其结果是:
is_nothrow_copy_constructible:
int: true
A: true
B: false
C: true
D: true
E: false
F: true
G: false我想知道为什么E是扔的,但是d不是。我猜:
我不知道我的猜测是否正确。我想知道在哪里可以找到std::is_nothrow_copy_constructible的实现
发布于 2017-12-10 12:24:46
让我们看看标准库的stdlibc++实现(可以在<type_traits>中找到):
template<typename _Tp, typename... _Args>
struct __is_nt_constructible_impl
: public integral_constant<bool, noexcept(_Tp(declval<_Args>()...))>
{ };
template<typename _Tp, typename _Arg>
struct __is_nt_constructible_impl<_Tp, _Arg>
: public integral_constant<bool,
noexcept(static_cast<_Tp>(declval<_Arg>()))>
{ };该实现只是检查对(复制)构造函数的调用是否为noexcept (通过使用运算符),并相应地从true_type或false_type继承。您的假设是正确的,编译器足够聪明地使默认构造函数为not,除非有可能,也就是说,它不必调用未标记为noexcept的成员对象的构造函数。
https://stackoverflow.com/questions/47738648
复制相似问题