gpt4 book ai didi

c++ - 为什么 std::queue::pop 不返回值。?

转载 作者:IT老高 更新时间:2023-10-28 11:57:05 30 4
gpt4 key购买 nike

我经历了这个page但我无法得到同样的原因。里面提到了

"it is more sensible for it to return no value at all and to requireclients to use front() to inspect the value at the front of the queue"

但是从front() 中检查一个元素也需要将该元素复制到左值中。例如在这个代码段中

std::queue<int> myqueue;
int myint;
int result;
std::cin >> myint;
myqueue.push (myint);
/* here temporary will be created on RHS which will be assigned to
result, and in case if returns by reference then result will be
rendered invalid after pop operation */
result = myqueue.front(); //result.
std::cout << ' ' << result;
myqueue.pop();

在第五行 cout 对象首先创建 myqueue.front() 的拷贝,然后将其分配给结果。那么,有什么区别,pop 函数可以做同样的事情。

最佳答案

So, whats the difference, pop function could have done the same thing.

它确实可以做同样的事情。之所以没有这样做,是因为在存在异常的情况下返回弹出元素的弹出是不安全的(必须按值返回并因此创建一个拷贝)。

考虑这种情况(用一个幼稚/虚构的流行实现来说明我的观点):

template<class T>
class queue {
T* elements;
std::size_t top_position;
// stuff here
T pop()
{
auto x = elements[top_position];
// TODO: call destructor for elements[top_position] here
--top_position; // alter queue state here
return x; // calls T(const T&) which may throw
}

如果 T 的复制构造函数在返回时抛出,你已经改变了队列的状态(top_position 在我的幼稚实现中)并且元素从队列中移除(并且不返回)。出于所有意图和目的(无论您如何在客户端代码中捕获异常),队列顶部的元素都会丢失。

当您不需要弹出的值(即,它创建了一个没人会使用的元素的拷贝)时,这种实现也是低效的。

这可以通过两个单独的操作(void popconst T& front())安全有效地实现。

关于c++ - 为什么 std::queue::pop 不返回值。?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25035691/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com