Error in output of a program using copy constructor

Viewed 34

I have a very simple query about a program i just made. If you execute this basic code :

#include <iostream>
#include <vector>

class Exam
{
public:
int b;

Example(int a)
{
    b = a;
}

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

int main()
{
std::vector<Exam> myvector;
Exam ex1(1);
Exam ex2(2);
myvector.push_back(ex1);
myvector.push_back(ex2);

return 1;
}

It generates the following output:

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

Why does the copy constructor of '1' is executed twice and copy constructor of '2' only once??

1 Answers

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.

Related