How do I use emplace vs push with std::stack?

In C++, std::stack is a container adaptor that provides a LIFO (Last In, First Out) data structure. You can add elements to a stack using the push method or the emplace method. While both methods achieve the result of adding an item to the stack, they have some differences in usage and performance.

The push method adds a copy of the element to the stack, whereas emplace constructs the element in place. This means that emplace can be more efficient, especially for complex objects, as it avoids the overhead of an additional copy operation.

Here is an example demonstrating the difference between push and emplace when adding elements to a stack:

#include <iostream> #include <stack> class MyClass { public: MyClass(int x) : value(x) { std::cout << "MyClass constructor called with value: " << x << std::endl; } int value; }; int main() { std::stack myStack; // Using push MyClass obj1(10); myStack.push(obj1); // A copy of obj1 is pushed onto the stack // Using emplace myStack.emplace(20); // Constructs MyClass(20) in place return 0; }

C++ std::stack push emplace stack example container adaptor