Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a std::vector constructor not call object constructors for each element?

Tags:

c++

My code resembles something along 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 hello prints out once. It seems to imply that the vector only allocates space for the element but doesn't construct it. How do I make it construct 10 A objects?

like image 579
hookenz Avatar asked Nov 30 '22 05:11

hookenz


2 Answers

The object is constructed only once, as you pass it to std::vector. Then this object is copied 10 times. You have to do a printf in the copy constructor to see it.

like image 94
SebastianK Avatar answered Dec 01 '22 18:12

SebastianK


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(d.i) { cout << "copy i=" << d.i << 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
like image 24
Šimon Tóth Avatar answered Dec 01 '22 18:12

Šimon Tóth