简体   繁体   中英

C++: extra copy constructor called

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM