可能 STL 迭代器方法抛出异常 [英] May STL iterator methods throw an exception

查看:28
本文介绍了可能 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 container
  • operator++ for a valid iterator
  • operator* or operator-> 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 迭代器方法抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆