简体   繁体   English

处理超出范围的指数

[英]Handling Out-of-Range Indices

For a container class, what should the expected behavior be when the user of the class tries to set a value that's outside the class's size? 对于容器类,当类的用户尝试设置超出类大小的值时,预期的行为应该是什么?

The method in question is a "replace" method (like operator[] ), rather than an "add" method (like operator+= ). 有问题的方法是“替换”方法(如operator[] ),而不是“add”方法(如operator+= )。

I could throw an out_of_range exception or I could just resize the container to accommodate the addition. 我可以抛出一个out_of_range异常,或者我可以调整容器大小以适应添加。

超出范围的异常在这里更合适,因为“替换”语义通常意味着调用者假定/断言在指定的索引处存在数据,而没有。

For std::vector::operator[] , a domain error causes undefined behavior. 对于std::vector::operator[] ,域错误会导致未定义的行为。 For std::map::operator[] , a domain error creates a new entry. 对于std::map::operator[] ,域错误会创建一个新条目。 I guess the design questions are: 我想设计问题是:

  • How expensive is it to extend the container? 扩展容器有多贵? That is, can you create just one item (like map::operator[] ), or do you have to create all of the intervening items (like vector::operator[] ) 也就是说,你可以只创建一个项目(比如map::operator[] ),或者你是否必须创建所有介入的项目(如vector::operator[]

  • How expensive is the range check, compared to the access function? 与访问功能相比,范围检查有多贵? In map , the range check is free once you've run the access function. map ,一旦运行了访问功能,范围检查就是免费的。 In vector the range check approximately doubles the cost off the access. vector ,范围检查大约使访问成本增加一倍。

Since you are designing the container, feel free to impose whichever pattern suits you and your customers. 由于您正在设计容器,因此请随意使用适合您和您的客户的任何模式。 Just be sure to document the behavior. 请务必记录行为。

In general, I prefer throwing out-of-range exception. 一般来说,我更喜欢抛出超出范围的异常。 If the users really want to expand the storage, offer them a method to do so. 如果用户确实想要扩展存储,请为他们提供一种方法。 This will eliminate many unintentional expansions, which could lead to more serious bugs. 这将消除许多无意的扩展,这可能导致更严重的错误。 This is just my opinion. 这只是我的看法。

One point not yet mentioned is that it may sometimes be useful to provide for a special one-over case to extend the class size. 尚未提及的一点是,提供特殊的一对一案例以扩展班级规模有时可能是有用的。 The idea is that a class may have an invariant that items[0] to item[length-1] have all been validly assigned. 这个想法是一个类可能有一个不变的项目[0]到项目[length-1]都已被有效地分配。 If one attempts to write to item[K], with K>=length+1, it may be necessary to create new items [length..K-1] with unknown values, breaking the class invariant. 如果有人试图写入项目[K],K> = length + 1,则可能需要创建具有未知值的新项[length..K-1],从而打破类不变量。 On the other hand, if one writes to item[length], one could increment length by one and maintain the class invariant. 另一方面,如果一个人写入item [length],则可以将长度增加一个并保持类不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM