why is copy constructor called for every element of vector when i use push_back?

61 Views Asked by At

i'm working on this exercise where i implement a class that holds a dynamically allocated built-in array (int*). i'm trying to implement the big 5 and i think it's working (it compiles and runs, anyway) but every time i add a new element to the vector containing objects of my class type (see main), it seems to call the copy constructor on all elements in the vector! (see the output below).

is this normal behavior for c++ vectors, or am i doing something wrong? thanks

class LargeTypeRaw
{
public:

     LargeTypeRaw(size_t initialSize = 10)
        : data{ new int[size] }, size{ initialSize }
     {
         std::cout << "normal constructor called" << std::endl;        
     }

     LargeTypeRaw(const LargeTypeRaw& other)
         : size{ other.size }, data{ new int[other.size]}
     {
         std::copy(other.data, other.data + other.size, data); 
         std::cout << "copy constructor called" << std::endl; 
     }

     LargeTypeRaw(LargeTypeRaw&& other)
         : size{ other.size }, data{ other.data }
     {
         std::cout << "move constructor called" << std::endl; 
         other.data = nullptr;
     }

     LargeTypeRaw& operator=(const LargeTypeRaw& other)
     {
         std::cout << "copy assignment operator called" << std::endl; 

         if (&other != this)
         {
             
             delete[] data;
             data = new int[other.size]; 
             std::copy(other.data, other.data+other.size, data); 
         }

         return *this; 
     }

     LargeTypeRaw& operator=(LargeTypeRaw&& other)
     {
         std::cout << "move assignment operator called" << std::endl; 

         if (&other != this)
         {
             delete[] data;
             data = other.data; 
             other.data = nullptr; 
         }

         return *this;   
     }
 
    ~LargeTypeRaw()
    {
        std::cout << "destructor called " << std::endl; 
        delete [] data;
    }

    size_t getSize() const
    {
        return size; 
    }

    bool operator<(const LargeTypeRaw& rhs) const
    {
        return size < rhs.size; 
    }


private:
    int* data;
    size_t size; 
};




int main()
{
    
    //example using LargeTypes that hold int
    std::vector<LargeTypeRaw> vec{};

    for (int i = 0; i < 5; i++)
    {
        size_t size = rand() % 10;
        std::cout << "initializing another object " << std::endl;
        LargeTypeRaw lt{ size }; 
        std::cout << "adding the new object to the vector " << std::endl; 
        vec.push_back(lt);
    }

    
}

enter image description here

0

There are 0 best solutions below