为什么std :: queue :: pop没有返回值。 [英] Why doesn't std::queue::pop return value.?

查看:344
本文介绍了为什么std :: queue :: pop没有返回值。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我浏览了这个网页,但我无法得到相同的原因。有人提到

I went through this page but I am not able to get the reason for the same . There it is mentioned that


它更为明智的是它根本不返回任何值,并要求
客户端使用front()检查队列前面的值

"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"

但是从前面检查一个元素被复制在左值。例如在此代码段中

But inspecting an element from front() also required that element to be copied in lvalue. For example in this code segment

std::queue<int> myqueue;
int myint;
int result;
std::cin >> myint;
myqueue.push (myint);

/ *这里临时将创建在RHS上,将分配给结果,如果
如果通过引用返回,则结果将在弹出操作后被渲染无效* /

/* 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();

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

on fifth line cout object first creates a copy of myqueue.front() then assigns that to result. So, whats the difference, pop function could have done the same thing.

推荐答案


差异,pop函数可以做同样的事情。

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

它可以做同样的事情。之所以没有,是因为返回popped元素的弹出窗口在存在异常时是不安全的(必须通过值返回,从而创建副本)。

It could indeed have done the same thing. The reason it didn't, is because a pop that returned the popped element is unsafe in the presence of exceptions (having to return by value and thus creating a copy).

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 throws返回,你已经改变了队列的状态( top_position 在我的naive实现)和元素从队列中删除(不返回)。对于所有的意图和目的(无论如何捕获客户端代码中的异常),队列顶部的元素将丢失。

If the copy constructor of T throws on return, you have already altered the state of the queue (top_position in my naive implementation) and the element is removed from the queue (and not returned). For all intents and purposes (no matter how you catch the exception in client code) the element at the top of the queue is lost.

此实现在

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

This can be implemented safely and efficiently, with two separate operations (void pop and const T& front()).

这篇关于为什么std :: queue :: pop没有返回值。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆