Why copy constructor is invoked for vector emplace whereas copy constructor is not invoked for set?

Viewed 74

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--
1 Answers

All values in the vector must be in contiguous memory, by definition. Adding values to a vector means that, every once in a value, all values in the vector get reallocated to accomodate more values. Each reallocation reserves additional memory for further growth, and once the extra values get used up the vector gets reallocated again. That's the capsule summary of how a vector works.

In this case the vector already has one value in it before emplace() gets called.

The extra copy-construction is actually the result of the vector reallocating its contents -- the one existing value -- as part of emplace()ing a new value in the vector. This is done by copy-constructing the value in the reallocated vector.

std::set does not reallocate its contents, so none of this happens.

Related