Doesn't the std :: vector constructor call object constructors for each element?

My code resembles something in these lines.

class A { public: A(int i) { printf("hello %d\n", i); } ~A() { printf("Goodbye\n"); } } std::vector(10, A(10)); 

I notice that hi prints once. Apparently, it is implied that the vector allocates space for the element but does not create it. How do I create 10 objects A?

+4
source share
4 answers

An object is created only once when you pass it to std :: vector. Then this object is copied 10 times. You must do printf in the copy constructor to see it.

+12
source

You forgot the copy constructor:

 #include <iostream> #include <vector> using namespace std; class A { int i; public: A(int d) : i(d) { cout << "create i=" << i << endl; } ~A() { cout << "destroy" << endl; } A(const A& d) : i(di) { cout << "copy i=" << di << endl; } }; int main() { vector<A> d(10,A(10)); } 

Output:

 create i=10 copy i=10 copy i=10 copy i=10 copy i=10 copy i=10 copy i=10 copy i=10 copy i=10 copy i=10 copy i=10 destroy destroy destroy destroy destroy destroy destroy destroy destroy destroy destroy 
+6
source

A(10) creates a temporary object. Just one time. 10 elements of your vector are built using copy-constructor . Therefore, if you define a copy constructor for print B, you get 10 B.

+3
source

Define a copy constructor and everything will be fine:

 #include <cstdio> #include <vector> class A { public: A(int i) { printf("hello %d\n", i); } ~A() { printf("Goodbye\n"); } A(const A&) { printf("copy constructing\n"); } }; int main() { std::vector< A > a( 10, A(5) ); } 
+1
source

All Articles