为什么在STL中允许未定义的行为? [英] Why is undefined behavior allowed in the STL?

查看:162
本文介绍了为什么在STL中允许未定义的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认情况下, std :: stack 的底层容器是 std :: deque 。因此, std :: deque 的未定义行为是 std :: stack 的未定义行为。 cppreference 和其他网站在描述成员函数的行为时使用有效的术语。我认为这意味着它是为所有意图和目的。因此,调用 top() pop()等效于调用 pop_back(),并且在空容器上调用这些是未定义的行为。



从我的理解,为什么它是未定义的行为的原因是保留无投保证。我的理由是 operator [] std :: vector 有一个无throw保证,大小大于N,但是 at()有很强的保证,并且如果n是,则throws std :: out_of_range out of bounds。



所以我的问题是,一些事情背后的原理是什么可能未定义的行为和有无抛出保证与有强保证但抛出异常

解决方案

当允许未定义的行为时,为了效率的原因通常 >

如果标准指定了当您访问数组超出边界时必须发生的事情,它将强制实现检查索引是否在边界。这同样适用于一个向量,它只是一个动态数组的包装器。



在其他情况下,允许未定义行为以允许自由的实现。但是,这也是真正的效率(因为一些可能的实现策略在一些机器上比在其他机器上更有效,而C ++如果他们愿意,可以选择最有效的策略)。


By default, the "underlying container" of an std::stack is an std::deque. Therefore anything that is undefined behavior for a std::deque is undefined behavior for a std::stack. cppreference and other sites use the terminology "effectively" when describing the behavior of member functions. I take this to mean that it is for all intents and purposes. So therefore, calling top() and pop() is equivalent to calling back() and pop_back(), and calling these on an empty container is undefined behavior.

From my understanding, the reason why it's undefined behavior is to preserve the no-throw guarantee. My reasoning is that operator[] for std::vector has a no-throw guarantee and is undefined behavior if container size is greater than N, but at() has a strong guarantee, and throws std::out_of_range if n is out of bounds.

So my question is, what is the rationale behind some things having possibly undefined behavior and having a no throw guarantee versus having a strong guarantee but throwing an exception instead?

解决方案

When undefined behaviour is allowed, it's usually for reasons of efficiency.

If the standard specified what has to happen when you access an array out of bounds, it would force the implementation to check whether the index is in bounds. Same goes for a vector, which is just a wrapper for a dynamic array.

In other cases the behaviour is allowed to be undefined in order to allow freedom in the implementation. But that, too, is really about efficiency (as some possible implementation strategies could be more efficient on some machines than on others, and C++ leaves it up to the implementer to pick the most efficient strategy, if they so desire.)

这篇关于为什么在STL中允许未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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