When I run this code:
#include <iostream>
#include <vector>
#include <memory>
struct X {
X() { std::cout << "X()" << std::endl; }
X(const X&) { std::cout << " X(const X&)" << std::endl; }
X& operator=(const X& orig) {
std::cout << " X& operator=" << std::endl;
}
~X() { std::cout <<"~X()" << std::endl; }
};
int main(int argc, char const *argv[])
{
std::vector<X> vec;
for (int i = 0; i < 3; ++ i) {
vec.push_back(X());
std::cout << "==========" << std::endl;
vec.emplace_back(X());
std::cout << "**********" << std::endl;
}
return 0;
}
The output is:
I don't know why it would be like this. What is the difference between push_back() and emplace_back()? How does the vector allocate the memory?