There is some code:
A a1; A a2; A a3; std::vector<A> a; std::cout << "Push back a1" << std::endl; a.push_back(a1); std::cout << "Push back a2" << std::endl; a.push_back(a2); std::cout << "Push back a3" << std::endl; a.push_back(a3); And of course class A.
class A { static int ACount; private: public: A() { std::cout << "Constructor called. Objects = " << ++ACount << std::endl; } ~A() { std::cout << "Destructor called. Objects = " << --ACount << std::endl; } A(const A &a) { std::cout << "Copy Constructor called. Objects = " << ++ACount << std::endl; } }; int A::ACount; The output from the console is:
Constructor called. Objects = 1 Constructor called. Objects = 2 Constructor called. Objects = 3 Push back a1; Copy constructor called. Objects = 4 Push back a2; Copy constructor called. Objects = 5 Copy constructor called. Objects = 6 Destructor called. Objects = 5 Push back a3; Copy constructor called. Objects = 6 Copy constructor called. Objects = 7 Copy constructor called. Objects = 8 Destructor called. Objects = 7 Destructor called. Objects = 6 Destructor called. Objects = 5 Destructor called. Objects = 4 Destructor called. Objects = 3 Destructor called. Objects = 2 Destructor called. Objects = 1 Destructor called. Objects = 0 I can not understand why when I call the Push_back method (a2), the copy constructor is called 2 times, and when Push_back (a3), 3 times. I am trying to create a kind of graph of the engine and the creation / destruction of such a number of objects is very harmful to me. How to be? Or is it worth looking for some other container?
std::vector<A> a;calla.reserve(10);and see the results ... - Harry