Search code examples
copy-constructorpush-back

Copy constructor get called more than one time


Below code outputs:

Default ctor is called
Copy ctor is called
Default ctor is called
Copy ctor is called
Copy ctor is called

Why for each push_back() the calling of copy constructor incremented by 1? I think it should only be called one time. Is there something which i miss here? please i need detailed explanation.

class A
{
public:
    A()
    {
        std::cout << "Default ctor is called" << std::endl;
    }
    A(const A& other)
    {
        if(this != &other)
        {
            std::cout << "Copy ctor is called" << std::endl;
            size_ = other.size_;
            delete []p;
            p = new int[5];
            std::copy(other.p, (other.p)+size_, p);
        }
    }
    int size_;
    int* p;
};
int main()
{
    std::vector<A> vec;
    A a;
    a.size_ = 5;
    a.p = new int[5] {1,2,3,4,5};
    vec.push_back(a);

    A b;
    b.size_ = 5;
    b.p = new int[5] {1,2,3,4,5};
    vec.push_back(b);

    return 0;
}

Solution

  • This is because the push_back in your example has to do a reallocation every time. If you reserve the size in advance then you see only one copy.

    std::vector<A> vec;
    vec.reserve(10);