可以“移动"广告素材吗?队列中的对象,如果要从中弹出? [英] Is it okay to "Move" an object from a queue, if you're about to pop from it?

查看:61
本文介绍了可以“移动"广告素材吗?队列中的对象,如果要从中弹出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究commands的解析器(它们是围绕大量数据的精美包装器),并且有一个队列,未处理的命令驻留在该队列上.如果需要命令,可以使用以下代码查询它:

I've been working on a parser for commands (which are fancy wrappers around large arrays of data), and have a queue that unhandled commands reside on. If I need a command, I query it with code like this:

boost::optional<command> get_command() {
    if (!has_command()) return boost::optional<command>(nullptr);
    else {
        boost::optional<command> comm(command_feed.front()); //command_feed is declared as a std::queue<command>
        command_feed.pop();
        return comm;
    }
}

问题是,在适当的情况下,这些命令的大小可能为兆字节,并且需要非常快地进行解析.我的想法是我可以像这样优化移动:

The problem is, these commands could be megabytes in size, under the right circumstances, and need to parse pretty quickly. My thought was that I could optimize the transferal to a move like so:

boost::optional<command> get_command() {
    if (!has_command()) return boost::optional<command>(nullptr);
    else {
        boost::optional<command> comm(std::move(command_feed.front())); //command_feed is declared as a std::queue<command>
        command_feed.pop();
        return comm;
    }
}

这似乎适用于此特定情况,但这可以用作任何正确维护的RAII对象的通用解决方案,还是我应该做其他事情?

And it seems to work for this specific case, but can this be used as a general purpose solution to any properly maintained RAII object, or should I be doing something else?

推荐答案

是的,这是绝对安全的:

Yes, this is perfectly safe:

std::queue<T> q;
// add stuff...

T top = std::move(q.front());
q.pop();

pop()q中具有指定状态的第一个元素没有任何先决条件,并且由于您随后不使用q.front(),因此不必处理使该对象无效的任何情况.更多的.

pop() doesn't have any preconditions on the first element in the q having a specified state, and since you're not subsequently using q.front() you don't have to deal with that object being invalidated any more.

听起来不错!

这篇关于可以“移动"广告素材吗?队列中的对象,如果要从中弹出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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