push() powoduje skopiowanie przekazanego argumentu.
emplace() utworzenie elementu w odpowiednim miejscu na podstawie przekazanych argumentów.
Najlepiej poznać to na żywym przykładzie
#include <iostream>
#include <stack>
class X {
public:
X(int liczba, std::string napis);
X(const X& other);
private:
int mLiczba;
std::string mNapis;
};
X::X(int liczba, std::string napis) :
mLiczba(liczba),
mNapis(napis)
{
std::cout << "Konstruktor " << liczba << " " << napis << std::endl;
}
X::X(const X &other) :
mLiczba(other.mLiczba),
mNapis(other.mNapis)
{
std::cout << "Konstruktor kopiujacy " << mLiczba << " " << mNapis << std::endl;
}
int main() {
std::stack<X> stack;
std::cout << "Test push()" << std::endl;
stack.push(X(1, "jeden"));
std::cout << "Test emplace()" << std::endl;
stack.emplace(2, "dwa");
return 0;
}
Zwróć uwagę na argumenty przekazane do funkcji push() i emplace()
Output:
Test push()
Konstruktor 1 jeden
Konstruktor kopiujacy 1 jeden
Test emplace()
Konstruktor 2 dwa