I tested the following code:
#include <iostream>
#include <vector>
class foo {
public:
int m_data;
foo(int data) : m_data(data) {
std::cout << "parameterised constructor" << std::endl;
}
foo(const foo &other) : m_data(other.m_data) {
std::cout << "copy constructor" << std::endl;
}
};
main (int argc, char *argv[]) {
std::vector<foo> a(3, foo(3));
std::vector<foo> b(4, foo(4));
//std::vector<foo> b(3, foo(4));
std::cout << "a = b" << std::endl;
a = b;
return 0;
}
I get
parameterised constructor
copy constructor
copy constructor
copy constructor
parameterised constructor
copy constructor
copy constructor
copy constructor
copy constructor
a = b
copy constructor
copy constructor
copy constructor
copy constructor
However, if I replace std::vector<foo> b(4, foo(4)); by std::vector<foo> b(3, foo(4)); the copy constructor is not called by a = b and the output is
parameterised constructor
copy constructor
copy constructor
copy constructor
parameterised constructor
copy constructor
copy constructor
copy constructor
a = b
Why is in this case the copy constructor not called?
I’m using g++ (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1
In the first case,
aneeds to grow when you assign to it, which means that all its elements must be reallocated (and therefore destructed and constructed).In the second case,
adoes not need to grow, hence the assignment operator is used.See http://ideone.com/atPt9; adding an overloaded copy assignment operator that prints a message, we get the following for the second example: