Here is my simple program on emplace. When I use emplace on vector, I see that the Copy constructor is invoked. However, when I use emplace on set, I don't see that the copy constructor is invoked. What concept am I missing here?
#include <iostream>
#include <vector>
#include <set>
using namespace std;
class MyData
{
private:
int x;
public:
int getX()
{
return x;
}
MyData(int val): x(val) { cout<<"Constructor invoked--"<<endl; }
MyData(const MyData &rhs) { cout<<"Copy Constructor Invoked"<<endl; x = rhs.x; }
bool operator<(const MyData &lhs) const { return lhs.x < x; }
};
int main(int argc, char **argv)
{
MyData d1(5);
cout<<d1.getX()<<endl;
vector<MyData> vx;
auto it = vx.begin();
vx.insert(it,d1);
cout<<"Calling emplace for vector"<<endl;
vx.emplace_back(15);
set<MyData> mySet;
cout<<"mySet emplace invoking"<<endl;
mySet.emplace(20);
return 0;
}
Here are my results.
./emplace.out
Constructor invoked--
5
Copy Constructor Invoked
Calling emplace for vector
Constructor invoked--
Copy Constructor Invoked
mySet emplace invoking
Constructor invoked--