C++ 我从空标准容器的 front() 得到什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/681725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What do I get from front() of empty std container?
提问by Hymanhab
If front()
returns a reference and the container is empty what do I get, an undefined reference? Does it mean I need to check empty()
before each front()
?
如果front()
返回一个引用并且容器是空的,我会得到什么,一个未定义的引用?这是否意味着我需要empty()
在每个之前检查front()
?
回答by
You get undefined behaviour - you need to check that the container contains something using empty() (which checks if the container is empty) before calling front().
你得到未定义的行为——你需要在调用 front() 之前使用 empty()(检查容器是否为空)检查容器是否包含某些东西。
回答by graham.reeds
You get undefined behaviour.
你得到未定义的行为。
To get range checking use at(0). If this fails you get a out_of_range
exception.
要进行范围检查,请使用 at(0)。如果这失败了,你会得到一个out_of_range
例外。
回答by Arun R
Yes, you can use 'at' like Graham mentioned instead of using front.
是的,您可以像 Graham 提到的那样使用“at”,而不是使用 front。
But, at(0) is only available for some containers - vectors, deque and not for others - list, queue, stack. In these cases you've to fall back on the safety of the 'empty' check.
但是, at(0) 仅适用于某些容器 - 向量、双端队列,而不适用于其他容器 - 列表、队列、堆栈。在这些情况下,您必须依靠“空”支票的安全性。
回答by yves Baumes
You've always have to be sure your container is not empty before calling front() on this instance. Calling empty() as a safe guard is good.
在此实例上调用 front() 之前,您始终必须确保您的容器不为空。调用 empty() 作为安全保护是好的。
Of course, depending on your programm design, always having a non-empty container could be an invariant statement allowing you to prevent and save the call to empty() each time you call front(). (or at least in some part of your code?)
当然,根据你的程序设计,总是有一个非空的容器可能是一个不变的语句,允许你在每次调用 front() 时阻止和保存对 empty() 的调用。(或至少在您的代码的某些部分?)
But as stated above, if you want to avoid undefinied behavior in your program, make it a strong invariant.
但是如上所述,如果您想避免程序中的未定义行为,请使其成为强不变量。
回答by anil
Undefined Behaviour
未定义的行为