19

What are the differences between <queue>'s emplace and push?

here's explanation about the std::queue::emplace and std::queue::push .

Both methods add element after its current last element, return None.

Dami.h
  • 221
  • 1
  • 2
  • 7
  • 1
    Does this answer your question? [C++: Stack's push() vs emplace()](https://stackoverflow.com/questions/26198350/c-stacks-push-vs-emplace) – Lavish Saluja Nov 28 '19 at 11:42

1 Answers1

27

push() adds a copy of an already constructed object into the queue as a parameter, it takes an object of the queue's element type.

emplace() constructs a new object in-place at the end of the queue. It takes as parameters the parameters that the queue's element types constructor takes.

If your usage pattern is one where you create a new object and add it to the container, you shortcut a few steps (creation of a temporary object and copying it) by using emplace().

Mukul
  • 139
  • 4
  • 12
Sami Sallinen
  • 2,838
  • 12
  • 16
  • Hi @Sami, just so that it is clear, say if i have a queue of the type of user-defined-class, I would have created the object beforehand and then used emplace, whereas in push, I just pass the arguments I would normally pass to its constructor of the user-defined class I made? – Anshuman Kumar Jun 14 '20 at 06:46
  • which raises the question why would anyone use emplace? – Anshuman Kumar Jun 14 '20 at 06:46
  • 1
    Hi @Anshuman, I think you maybe mixed the concepts of push & emplace in your 1st message. Both methods still have legitimate use cases. You'd still use push e.g. if you have the object already at hand. – Sami Sallinen Jun 14 '20 at 08:03