I’m going through C++ FAQ by Marshall Cline.
Currently playing around with code in point 10.5.
I have this:
class Fred
{
public:
Fred();
Fred(int x, int y)
{
std::cout << "Fred with two ints\n" << std::endl;
};
};
int main()
{
std::vector<Fred>(3, Fred(4,5));
return 0;
}
I expected to see “Fred with two ints” printed 3 times – but it’s only printed once.
Why is that – is it not invoked 3 times?
This is the signature of the
vectorconstructor you are invoking:Fred(4,5)calls your defined constructor once, and the created instance is passed by reference to thevector<Fred>constructor. Then, it [the created instance] is copied 3 times to the vector. The copy operation is performed by using (default) copy constructor; so your constructor is not called more than once.