simple question about copy constructors

Hello everyone!

I have a very simple question. If you execute this simple code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <vector>

class Example
{
public:
    int a_;

    Example(int a)
    {
        a_ = a;
    }

    Example(const Example &other)
    {
        printf("Copy constructor of %d\n", other.a_);
        a_ = other.a_;
    }
};

int main()
{
    std::vector<Example> myvector;
    Example example1(1);
    Example example2(2);
    myvector.push_back(example1);
    myvector.push_back(example2);

    return 1;
}


You will get this output :

1
2
3
Copy constructor of 1
Copy constructor of 2
Copy constructor of 1


Why the the copy constructor of '1' is exectued two times and copy constructor of '2' only once??

Thank you!!
Try adding the line
myvector.reserve(2);
immediately after your declaration
std::vector<Example> myvector;

Something seems to be going on behind the scenes when the vector has to resize itself to allow push_back of the second example.
Last edited on
Yes lastchance! You were right. Good idea to try to always resize the vector whenever possible.

Thank you very much lastchance!
Actually I don't know that I am right ... I'm sure that the issue is to do with resizing, but I'm hazy on which type of constructor (copy, move, ... ) would be called at that point.

always resize the vector whenever possible

Actually, I wouldn't! I only put that there to determine if it was something to do with the resizing. I wouldn't advocate it in general: just live with the fact that the copy constructor gets called a few extra times. Often/mostly you wouldn't know what size to reserve.
Topic archived. No new replies allowed.