首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >std::is_nothrow_copy_constructible的实现是什么?

std::is_nothrow_copy_constructible的实现是什么?
EN

Stack Overflow用户
提问于 2017-12-10 12:04:31
回答 1查看 565关注 0票数 2

我读过可构造性,并了解到我们可以使用这个函数来检查复制构造函数是否抛出。我写了一些演示如下:

代码语言:javascript
复制
#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;
}

其结果是:

代码语言:javascript
复制
is_nothrow_copy_constructible:
int: true
A: true
B: false
C: true
D: true
E: false
F: true
G: false

我想知道为什么E是扔的,但是d不是。我猜:

  1. 如果一个自定义复制构造函数声明为to除外,那么std::is_nothrow_copy_constructible将假设它是nothrow,否则它将被抛出。
  2. 如果一个类包含一些复制构造函数可能抛出的数据成员,则该类的默认副本构造函数是可抛出的,例如类E。

我不知道我的猜测是否正确。我想知道在哪里可以找到std::is_nothrow_copy_constructible的实现

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-12-10 12:24:46

让我们看看标准库的stdlibc++实现(可以在<type_traits>中找到):

代码语言:javascript
复制
  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_typefalse_type继承。您的假设是正确的,编译器足够聪明地使默认构造函数为not,除非有可能,也就是说,它不必调用未标记为noexcept的成员对象的构造函数。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47738648

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档