1
#include <stdio.h>
#include <string>
#include <iostream>
#include <vector>

using namespace std;

class MyInt
{
    int* a;
    int length;

  public:
     MyInt();
     explicit MyInt(int length);
     MyInt(const MyInt&);
     MyInt& operator=(const MyInt&);
    ~MyInt();
};

// MyInt.cpp
MyInt::MyInt():a(NULL)
{
    std::cout <<"Default Constructor"<<std::endl;
}

MyInt::MyInt(int size):length(size),a(new int[size])
{
         std::cout<<"Parameterized Constructor"<<std::endl;
}

MyInt::MyInt(const MyInt& obj)
{

    std::cout<<"Copy Constructor called"<<std::endl;
    length = obj.length;
    a = new int[length];
}

MyInt& MyInt::operator=(const MyInt& obj)
{
    if(this != &obj)
    {
         if(NULL != a)
         delete [] a;

         length = obj.length;
         a = new int[length];
    }
    return *this;
}

void printVector(std::vector<MyInt>& v1)
{
   // for(int* num : v1)
    //std:cout << num <<" ";

    //std::cout<<endl;
}

MyInt::~MyInt()
{
    if(NULL != a)
    delete [] a;
}

int main()
{


    std::vector<MyInt> v1,v2;

    for(int i = 0 ; i < 5 ; ++i)
    {
        // v1.push_back(MyInt(i+1));
        MyInt obj(i+1);
        v1.push_back(obj);
    }

    //Delete the heap before calling vector clear


    return 0;
}

The outpupt I expect is:

Parameterized Constructor
Copy Constructor called Parameterized Constructor
Copy Constructor called Parameterized Constructor
Copy Constructor called Parameterized Constructor
Copy Constructor called Parameterized Constructor
Copy Constructor called

The actual output is

Parameterized Constructor
Copy Constructor called
Parameterized Constructor
Copy Constructor called
Copy Constructor called
Parameterized Constructor
Copy Constructor called
Copy Constructor called
Copy Constructor called
Parameterized Constructor
Copy Constructor called
Parameterized Constructor
Copy Constructor called
Copy Constructor called
Copy Constructor called
Copy Constructor called
Copy Constructor called


What is the hidden truth for this, Could anyone help me better understand this?

Raju
  • 1,149
  • 1
  • 6
  • 19
  • 2
    When `std::vector` needs more space it copies all the elements from the old area to the new area. To avoid (minimise) this call `std::vector::reserve` before pushing many elements onto a vector. This pre-allocates the needed space. – Richard Critten Jul 26 '18 at 10:47
  • As stated above the std::vector resizes itself when it run out of space, this is when it needs to copy every element from the old memory to the new, bigger one. In addition to std::vector::reserve you can pass the minimum number of elements to the vectors constructor, this way it will allocate memory to hold all those objects. – Petok Lorand Jul 26 '18 at 10:50
  • Fun fact: if you add a move c’tor, it’ll call that when it reallocates. That is, `MyInt(MyInt&&)`. – Ben Jul 26 '18 at 12:13

0 Answers0