29

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
  • 321
  • 1
  • 3
  • 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

38

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().

Example

#include <iostream>
#include <stack>
using namespace std;

struct Point_3D
{
    int x, y, z;
    Point_3D(int x = 0, int y = 0, int z = 0)
    {
        this->x = x, this->y = y, this->z = z;
    }
};


int main()
{
    stack<Point_3D> multiverse;

    // First, Object of that(multiverse) class has to be created, then it's added to the stack/queue
    Point_3D pt {32, -2452};
    multiverse.push(pt);

    // Here, no need to create object, emplace will do the honors
    multiverse.emplace(32, -2452);

    multiverse.emplace(455, -3);
    multiverse.emplace(129, 4, -67);
}
HIMANSHU PANDEY
  • 684
  • 1
  • 10
  • 22
Sami Sallinen
  • 3,203
  • 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