当对象的当前状态不允许对其进行操作时抛出哪个异常?

Which exception to throw when current state of the object does not allow attempted operation on it?

假设我们正在实现一个行为类似于向量的自定义集合,并且我们希望 operator[] 在集合为空时抛出一些异常。 std::vector 在这种情况下有未定义的行为,但我们想抛出异常。如果这是 C#,我们可能会抛出 InvalidOperationException. But which C++ exception would be the most appropriate/intuitive in this case? I feel std::out_of_range 不是最佳选择,因为集合是空的,所以没有 'range' 索引 return 是有效的(任何) 元素。

std::vector::at 已经这样做了。所以你可以使用 at 方法而不是 operator []。它为无效索引抛出 std::out_of_range

请注意,您必须做大量工作才能达到 std::vector 的性能。但是如果你想坚持自己的容器并想从 [] 中抛出,那么像 at 方法 std::out_of_range 是标准异常 classes 中的最佳选择。否则你需要定义你自己的自定义异常 class.