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

查看:171
本文介绍了可能STL迭代器方法抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

析构函数不得抛出异常(所以堆栈展开可以在异常处理期间完成),并且必须释放分配给该对象的任何资源(因此无资源泄漏)。包含其他对象(或分配了多个资源)的对象的设计可能会在STL容器中记录指向它们的指针。因此,析构函数将使用以下与迭代器相关的方法:




  • begin() end()对于有效的迭代器

  • operator ++ / li>
  • operator * operator-> 用于有效的迭代器



但是为了保证析构函数都不会抛出异常并释放其资源,您将需要依赖这些方法从不抛出异常。 >

依靠这些方法永远不会抛出异常是安全的吗?很难想象一个可以抛出异常的实际实现,因为在这个引擎下,STL迭代器本质上是一个指针。但标准C ++ 要求那些方法永远不会抛出异常?我没有在C ++标准中找到一个清晰的陈述。






编辑:有趣的情况适用于C ++ 03,当您希望 指向资源的容器。有这样做的好理由例如,如果您有多态资源。由于BjörnPollex 在答案中指出,如果您使用资源的容器(例如 std :: list< Resource> )而不是指向资源的指针的容器,容器的析构函数将处理

解决方案


对于有效的迭代器的操作符++


C ++标准(我参考N3290草案)并不给予递增运算符的迭代器。



例如, std :: istreambuf_iterator :: operator ++ $ C>的std :: basic_streambuf :: sbumpc 。 sbumpc 可能会调用 uflow ,反过来可能会导致异常。


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() 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.

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.


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++ for a valid iterator

The C++ standard (I refer to N3290 draft) does not give nothrow guarantee for increment operator of iterators.

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天全站免登陆