May STL iterator methods throw an exception(可能 STL 迭代器方法抛出异常)
问题描述
析构函数可能不会抛出异常(所以 stack unwinding 可以在异常处理期间完成),并且必须释放分配给对象的任何资源(因此不会出现资源泄漏).包含多个其他对象(或分配了多个资源)的对象的设计可能会在 STL 容器中记录指向它们的指针.因此,析构函数将使用以下与迭代器相关的方法:
Destructors may not throw exceptions (so stack unwinding can complete during exception handling), and must deallocate any resources allocated to the object (so no resources leak). A design for an object that contains several other objects (or is allocated several resources) might record pointers to them in an STL container. The destructor would therefore use the following iterator-related methods:
begin()
,end()
用于容器operator++
用于有效迭代器operator*
或operator->
用于有效迭代器
begin()
,end()
for the containeroperator++
for a valid iteratoroperator*
oroperator->
for a valid iterator
但是为了保证析构函数既不抛出异常又不释放其资源,您需要依赖那些从不抛出异常的方法.
But to guarantee that the destructor both does not throw exceptions and deallocates its resources you would need to rely on those methods never throwing exceptions.
依赖那些从不抛出异常的方法是否安全?很难想象会抛出异常的实际实现,因为在底层,STL 迭代器本质上是一个指针.但是标准 C++ 是否要求这些方法永远不会抛出异常?我在 C++ 标准中没有找到明确的声明.
Is it safe to rely on those methods never throwing exceptions? It is hard to imagine a practical implementation that would throw exceptions, as under the hood an STL iterator is essentially a pointer. But does standard C++ require that those methods never throw exceptions? I've not found a clear statement in the C++ standard.
编辑:当您想要 一个容器指针到资源.这样做是有充分理由的;例如,如果您有多态资源.正如 Björn Pollex 在他的回答中指出的那样,如果您使用资源容器(例如 std::list< Resource >
)而不是资源指针容器,容器的析构函数将负责销毁(解除分配)Resource
对象.
Edit: The interesting case is for C++ 03 when you want to have a container of pointers to resources. There are good reasons for doing this; for example, if you have polymorphic resources. As Björn Pollex points out in his answer, if you use a container of resources (such as a std::list< Resource >
) rather than a container of pointers to resources, the destructor of the container will take care of destruction (deallocation) of the Resource
objects for you.
推荐答案
operator++ 用于有效迭代器
operator++ for a valid iterator
C++ 标准(我指的是 N3290 草案)并没有为迭代器的增量运算符提供 nothrow 保证.
The C++ standard (I refer to N3290 draft) does not give nothrow guarantee for increment operator of iterators.
例如,std::istreambuf_iterator::operator++
对std::basic_streambuf::sbumpc
的调用有影响.sbumpc
可能会调用 uflow
而后者可能会抛出异常.
For example, std::istreambuf_iterator::operator++
effects in call to std::basic_streambuf::sbumpc
. The sbumpc
may call uflow
which in turn may throw exception.
这篇关于可能 STL 迭代器方法抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:可能 STL 迭代器方法抛出异常


基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 我有静态或动态 boost 库吗? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01