Is it okay to “Move” an object from a queue, if you're about to pop from it?

前端 未结 4 1522
耶瑟儿~
耶瑟儿~ 2021-01-01 11:15

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 nee

4条回答
  •  情书的邮戳
    2021-01-01 11:51

    Yes, this is perfectly safe:

    std::queue q;
    // add stuff...
    
    T top = std::move(q.front());
    q.pop();
    

    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.

    Sounds like a good idea to do!

提交回复
热议问题