【问题标题】:What is the implementation of std::is_nothrow_copy_constructible?std::is_nothrow_copy_constructible 的实现是什么?
【发布时间】:2017-12-10 20:24:46
【问题描述】:

我已阅读std::is_nothrow_copy_constructible,并了解到我们可以使用此函数来检查复制构造函数是否抛出。我写了一些演示如下:

#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 是 throw 而 d 不是。我猜:

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

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

【问题讨论】:

  • @bolov 我也读过,但觉得没什么帮助。
  • 什么是“无用”?他们给出了非常严格的定义以及可能的实现。
  • @bolov 这在某种程度上很有帮助。但我需要的是代码实现,既不是严格的定义,也不是可能的实现(不完整)。
  • 你有代码实现。 “可能的实现”是代码实现。并且是完整的。

标签: c++ c++11


【解决方案1】:

我们看一下标准库的stdlibc++实现(可以在&lt;type_traits&gt;找到):

  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(通过使用noexcept operator)并相应地从true_typefalse_type 继承。您的假设是正确的,编译器足够聪明,可以尽可能使默认构造函数为 noexcept,即,它不必调用未标记为 noexcept 的成员对象的构造函数。

【讨论】:

  • 非常感谢。虽然没有完全看懂,但是你已经明确了学习的方向
  • &lt;type_traits&gt;中的代码很难看懂。你能给我一些建议吗,或者你能告诉我任何解释 stdlibc++ 实现的书吗?再次感谢!
  • @selfboot 没有关于实现的书。您基本上必须了解模板和元编程的基础知识。阅读有关模板专业化和 SFINAE 的内容,您将正确理解代码。
猜你喜欢
  • 2017-10-27
  • 2021-06-08
  • 2020-12-03
  • 1970-01-01
  • 2018-11-04
  • 2021-05-21
  • 1970-01-01
  • 2012-06-02
相关资源
最近更新 更多