gpt4 book ai didi

c++ - std::vector 中的元素可以有抛出析构函数吗?

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

当我查看 Container它列出了对 cppreference 的要求 Destructible作为 value_type 的要求。这似乎暗示容器元素的析构函数可能不会抛出。

我无法在 C++14 标准中找到对这一要求的引用(没有查看旧版本)。我唯一能找到的是 value_type 必须是 Erasable这根本不意味着任何异常安全。

所以我的问题是,std::vector 中的元素可以有抛出析构函数吗?如果不是,标准中的哪个部分禁止它?


P.S.:别担心,我不打算创建带有抛出析构函数的类型。我只是在编写一个符合标准的实现,并试图获得正确的异常安全性。

最佳答案

N4140 [res.on.functions]/2 状态:

In particular, the effects are undefined in the following cases:

(2.1) — for replacement functions (18.6.1), if the installed replacement function does not implement the semantics of the applicable Required behavior: paragraph.

(2.2) — for handler functions (18.6.2.3, 18.8.3.1, D.11.1), if the installed handler function does not implement the semantics of the applicable Required behavior: paragraph

(2.3) — for types used as template arguments when instantiating a template component, if the operations on the type do not implement the semantics of the applicable Requirements subclause (17.6.3.5, 23.2, 24.2, 26.2). Operations on such types can report a failure by throwing an exception unless otherwise specified.

(2.4) — if any replacement function or handler function or destructor operation exits via an exception, unless specifically allowed in the applicable Required behavior: paragraph.

(2.5) — if an incomplete type (3.9) is used as a template argument when instantiating a template component, unless specifically allowed for that component.

这有点晦涩,但节省了大量空间,否则这些空间会浪费在整个库子句中的“T 必须满足可破坏性要求”语句上。

值得注意的是,这并不意味着 std::vector 的元素不能有抛出析构函数;这仅意味着从标准库调用时,所述析构函数绝不能抛出。所以例如该程序符合:

#include <vector>

struct A {
bool throw_an_int = false;
~A() noexcept(false) {
if (throw_an_int) throw 42;
}
};

int main() {
try {
A a;
a.throw_an_int = true;
std::vector<A> lots_of_As(42);
} catch(int&) {}
}

关于c++ - std::vector 中的元素可以有抛出析构函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26902006/

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