gpt4 book ai didi

c++ - ISO C++ 15.3.10 : Why is this undefined behaviour?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:59:25 25 4
gpt4 key购买 nike

来自相关的 c++ 标准部分:

Referring to any non-static member or base class of an object in the handler for a function-try-block of a constructor or destructor for that object results in undefined behavior.

例如。

T::~T() 
{
try {
this->nonstatic_member; // iff I read the quote correctly
} catch( ... ) {
}
}

那么为什么会出现这种未定义的行为呢?

最佳答案

我认为在析构函数 的函数尝试 block 中访问非静态数据成员的原因是 [except.ctor]/2 和 [except.handle]/11 保证当进入所述 try block 的 catch 子句时,所有子对象都已被销毁:

github draft from 2014-07-23, [except.ctor]/2

An object of any storage duration whose initialization or destructionis terminated by an exception will have destructors executed for allof its fully constructed subobjects (excluding the variant members ofa union-like class), that is, for subobjects for which the principalconstructor has completed execution and the destructor has not yetbegin execution.

[except.handle]/11

[...] The base classes and non-variant members ofan object shall be destroyed before entering the handler of afunction-try-block of a destructor for that object.

因此,无论我们在类本身的dtor中抛出异常,还是在子对象的dtor中抛出异常:所有子对象都会被销毁。


示例 1:

#include <iostream>

struct loud
{
~loud() { std::cout << "~loud()\n"; }
};

struct T
{
loud l;

~T() noexcept(false)
try
{
std::cout << "throwing an int\n";
throw 42;
}catch(int)
{
std::cout << "caught an int\n";
throw;
}
};

int main()
{
try
{
T t;
}catch(...)
{
std::cout << "caught an exception in main\n";
}
}

输出:

throwing an int~loud()caught an intcaught an exception in main

Live example


Example 2:

#include <iostream>

struct loud
{
loud() { std::cout << "loud()\n"; }
~loud() { std::cout << "~loud()\n"; }
};

struct A
{
A() { std::cout << "A()\n"; }
~A() noexcept(false) { std::cout << "~A()\n"; throw 42; }
};

struct T
{
loud l;
A a;

~T() noexcept(false)
try
{
}catch(int)
{
std::cout << "caught an int\n";
throw;
}
};

int main()
{
try
{
T t;
}catch(...)
{
std::cout << "caught an exception in main\n";
}
}

输出:

loud()A()~A()~loud()caught an intcaught an exception in main

Live example

关于c++ - ISO C++ 15.3.10 : Why is this undefined behaviour?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25094103/

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