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

标签 c++ stl

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

"it is more sensible for it to return no value at all and to require clients 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/

相关文章:

C++ shared_ptr use_count for nullptr

c++ - 在 VS 中移动 [eax+4]

c++ - 为什么 C++ 中的 set::end 迭代器取消引用集合中的元素数量?

c++ - 如何按不同 std::vector 的值对 std::vector 进行排序?

c++ - 使用 STL 在 list<MyStruct> 中查找成员的最小值

c++ - 使用动态大小时,二维 vector 中的 push_back() 会出错

c++ - 在不包含在另一个范围内的范围内找到第一个元素

c++ - 程序不计算记录数

c++ - 将元素从一个数组复制到另一个 C++

c++ - 在 C++11 中使用什么更好,零或 NULL?