jeudi 20 mai 2021

This might be a naive question but in simple terms how to implement a copy constructor same as std::vector?

I have a simple Box container with a naive implementation that takes Car

#include <iostream>
#include <vector>

struct Car { 
    Car() { puts("def"); }
    Car(Car const& other) { puts("copy"); }
    Car& operator=(Car const& other) {
        puts("assign");
        return *this;
    }
};


struct Box {
    size_t size;
    Car* ptr;

    Box(size_t size) 
        : size(size)
        , ptr{new Car[size]} 
        {}
    
    Box(Box const& other) 
        : size{other.size} 
        {
            ptr = new Car[size];
            for (int i = 0; i < size; i++)
                ptr[i] = other.ptr[i]; // hits operator=
    }
};

int main() {
    Box b(2);
    Box b3 = b;    
    std::cout << std::endl;

    std::vector<Car> v(2);
    std::vector<Car> v2 = v;
}

o/p

def
def
def
def
assign
assign

def
def
copy
copy
  • std::vector copies and calls the copy constructor and Box doesn't. How std::vector's copy constructor is implemented? and what I am doing wrong?
  • How std::vector's memory allocation is handled and why default constructor is called only two times in std::vector where as 4 times in Box? Any explanation would suffice

Aucun commentaire:

Enregistrer un commentaire