毫无例外地处理 STL 错误

发布于 2024-09-25 23:21:51 字数 134 浏览 0 评论 0原文

我有一个项目大量使用STL。现在我正在努力将项目移植到不支持异常的特定平台。我可以禁用异常,但我仍然需要处理 STL 错误。

是否有任何方法可以在禁用异常的情况下正确处理 STL 错误?是否有任何第三方 STL 实现可以帮助解决这个问题?

I have a project which uses STL a lot. Now I'm working on porting the project to a specific platform which doesn't support exceptions. I can disable exceptions, however I still need to handle STL errors.

Is there any approach to handle STL errors correctly with exceptions disabled? Is there any third party STL implementation which helps with it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜中书 2024-10-02 23:21:51

使用现有的 std 库容器并在禁用异常的情况下进行编译的问题是 std 容器接口本身假设启用了异常。使用异常,如果无法获取内存,operator new 会抛出异常,没有异常,operator new 会返回 0,这是 std 容器无法处理的。

一种方法是仅使用STL算法+向量。您可以使用它复制其他容器大约 95% 的操作。问题是大多数 STL 实现都假设

v.reserve(v.size()+1);
assert(v.size()+1<=v.capacity());

永远不会断言(因为如果没有内存,保留将抛出异常)。为了确保这种情况永远不会抛出,我使用了“固定容量”容器,即在编译时容量固定的容器。基本上这些是我传入特殊分配器的向量。然后你可以在插入之前检查容器的 max_size() 。然后避免使用像 at() 这样的东西。为了获得更好的预测性,请使用 basic_string 而不是向量。这迫使您只存储 POD 类型,在复制或默认构造时永远不会抛出异常。另外,内存需求更容易计算。

另一种方法是使用侵入式容器。这些不会抛出(可能除了误用接口之外),因为它们从一开始就不会获取内存。

The problem with taking an existing std library coontainer and compiling with exceptions disabled is that the the std container interfaces themselves assume exceptions are enabled. Using exceptions, operator new will throw if it cannot acquire memory, without exceptions, operator new returns a 0 instead, which std containers cannot handle.

One approach is to only use STL algorithms + vector. You can replicate about 95% of what the other containers do using this. The problem is that most STL implementations assume that

v.reserve(v.size()+1);
assert(v.size()+1<=v.capacity());

will never assert (since reserve will throw if there is no memory). To insure this never throws, I have used "fixed capacity" containers, i.e. containers with a capacity fixed at compile time. Basically these are vectors where I pass in a special allocator. Then you can check the max_size() of the container before insertion. Then just avoid using things like at(). For even better predicatbilty, use basic_string instead of vector. This forces you to only store POD types, which never throw when copied or default constructed. Plus memory requirements are easier to compute.

Another approach is to use intrusive containers. These don't throw (outside of misuse of the interface perhaps), since they never acquire memory in the first place.

秉烛思 2024-10-02 23:21:51

可能旧版本的 stlport 可以配置为不使用异常。这显然是非标准的,但满足您的要求。

Possibly an old version of stlport can be configured not to use exceptions. This obviously is non-standard but satisfies your requirement.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文