gpt4 book ai didi

c++ - 编译器为类生成 noexcept ctor,其成员在没有此类保证的情况下构造

转载 作者:太空宇宙 更新时间:2023-11-03 10:41:25 25 4
gpt4 key购买 nike

考虑一个例子:

class ClassThatMayThrowInCtor
{
ClassThatMayThrowInCtor()
{
if (g_unlucky) throw "Exception";
}
};

class Aggregate
{
ClassThatMayThrowInCtor m_member;
};

据我所知,在某些情况下,C++14 中的编译器可能会生成一个默认构造函数,即 noexcept

它会在这种情况下,还是会理解,因为成员的默认 ctor 不提供任何此类保证,所以它也不应该?


要求引用上述声明(在某些情况下...),我未能在标准中找到它,但是 Andrzej's blog确实提到:

This does not mean that noexcept is useless. Compiler will annotate implicitly generated member functions of your classes (constructors, copy and move assignments and destructor) with noexcept, as appropriate, and STL components will be querying for this annotation. The feature will enable significant optimizations (by using move constructors) even though you will not see a single noexcept keyword. And when compiler annotates functions with noexcept it does it correctly (except for destructors), so there is no risk that some noexcept move constructor will throw.

(强调我的)

最佳答案

来自[except.spec]:

14 - [...] If f is [...] an implicitly declared default constructor [...] f allows all exceptions if any function it directly invokes allows all exceptions, and f has the exception-specification noexcept(true) if every function it directly invokes allows no exceptions. [...]

Aggregate 的隐式声明默认构造函数直接调用 ClassThatMayThrowInCtor::ClassThatMayThrowInCtor() 允许所有异常,所以 Aggregate::Aggregate() 允许所有异常并且不是 noexcept

关于c++ - 编译器为类生成 noexcept ctor,其成员在没有此类保证的情况下构造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35991071/

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