1

understanding the concepts of copy constructor I can not explain the debug output of following simple test program:

#include <iostream>
#include <vector>
using std::cout, std::endl, std::vector;

class Module
{
private:
    char *name;

public:
    // ctor
    Module(char n);
    // copy ctor
    Module(const Module &m);
    // dtor
    ~Module();
};

Module::Module(char n)
{
    name = new char;
    *name = n;
    cout << "ctor " << n << endl;
}

// copy ctor
Module::Module(const Module &m)
    : Module{*m.name}
{
    cout << "copy ctr " << *name << endl;
}

Module::~Module()
{
    if (name != nullptr)
    {
        cout << "dtor " << *name << endl;
    }
    delete name;
}

int main()
{
    vector<Module> vec;
    vec.push_back(Module{'A'});
    vec.push_back(Module{'B'});

    return 0;
}

its output:

ctor A
ctor A
copy ctr A
dtor A
ctor B
ctor B
copy ctr B
ctor A
copy ctr A
dtor A
dtor B
dtor A
dtor B

I had expected following output:

ctor A
ctor A
copy ctr A
dtor A
ctor B
ctor B
copy ctr B
dtor B
dtor A
dtor B

if anyone knows I would like to know the reason for this behavior...

g++.exe (Rev5, Built by MSYS2 project) 10.2.0

thanks in advance!

1
  • It appears you are assuming that memory (and objects) are allocated by the vectors constructor. push_back() may also reallocate. Commented Jan 4, 2021 at 11:31

1 Answer 1

4

As you add items to your vector, it may be reallocated. This means new memory is allocated and items are copied from the old memory to the new memory. This process calls the copy constructor.

To prevent reallocation reserve the necessary memory beforehand.

vector<Module> vec;
vec.reserve(2);
vec.push_back(Module{'A'});
vec.push_back(Module{'B'});

Note (because it's often misunderstood) reserve does not change the size of the vector, it just allocates more memory so the vector can grow without needing to reallocate.

Sign up to request clarification or add additional context in comments.

1 Comment

that's make sense, I forgot the issue that vector allocates memory dynamically on push_back. thanks for the explanation!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.