gpt4 book ai didi

c++ - 构造函数被继承时的 std::is_nothrow_constructible

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:26:40 24 4
gpt4 key购买 nike

考虑以下两个示例:

struct A {
A () noexcept = default;
};

struct B : A {
B () noexcept = default;

template <typename T>
B (T) noexcept {}
};

struct C : A {
using A::A;

template <typename T>
C (T) noexcept {}
};

和用法:

std::cout << std::is_nothrow_constructible<B>::value << std::endl; // (X)
std::cout << std::is_nothrow_constructible<B, int>::value << std::endl;

std::cout << std::is_nothrow_constructible<C>::value << std::endl; // (Y)
std::cout << std::is_nothrow_constructible<C, int>::value << std::endl;

输出是:

1
1
0
1

使用的编译器:GCC 4.8.1。

因此,如果我显式编写默认的 B 构造函数,(X) 会生成 1,另一方面,如果默认的 C 构造函数可用由于继承,(Y) 产生 0。这是为什么?

这是否意味着在使用 is_nothrow_constructible 特征时不考虑继承的构造函数?

最佳答案

这里的问题是模板构造函数隐藏了继承的构造函数。来自§12.9/4:

A constructor so declared [...]. It is deleted if the corresponding constructor in X is deleted (8.4.3) or if a defaulted default constructor (12.1) would be deleted, [...].

以下编译没有问题:

struct C: A {
using A::A;
};
static_assert(std::is_nothrow_constructible<C>{}, "");

关于c++ - 构造函数被继承时的 std::is_nothrow_constructible,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41239062/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com