Max Frai
Max Frai

Reputation: 64266

Std vector resizing

I have some std::vector and I have to resize it with some default value. Here is the code:

static int Counter = 0;
class Data
{
   /* ... */
   Data() { 
      Counter++; 
      std::cout << Counter << std::endl;
   }
};

std::vector<Data> mArray;

for (int i=0; i <= 200; ++i)
{
   mArray.push_back(Data());
}

// And resizing somewhere:
std::cout << "Resizing!\n";
mArray.resize(400, Data());

As I understand, after inserting 200 items, I can resize it with resize function which takes new size and default value for each new element.

When I run that program I see:

0
1
2
...
199
200
Resizing
201

Why does only 1 item is inserted after resizing?

Upvotes: 4

Views: 2616

Answers (5)

Fred Larson
Fred Larson

Reputation: 62053

You're only seeing a count from your default constructor, when the entries being added are copy constructed. You'll have to add a copy constructor that counts copies as well:

   Data(const Data& other) { 
      // Actual copying code, whatever that may be
      Counter++; 
      std::cout << Counter << std::endl;
   }

Upvotes: 12

Zac Howland
Zac Howland

Reputation: 15872

You are printing out Counter++, not the size of your vector (since only 1 Data object is created to initialize the rest of the vector, it only gets incremented once).

Upvotes: 2

Frederik Slijkerman
Frederik Slijkerman

Reputation: 6529

Because the other 199 Data instances are created by copying the Data instance that you pass to resize() via its copy constructor.

Upvotes: 2

Eric Fortin
Eric Fortin

Reputation: 7603

Because resize will use the copy constructor to insert new elements and for this reason, the default constructor is called only once.

Upvotes: 3

Etienne de Martel
Etienne de Martel

Reputation: 36852

Because the default constructor is called once: std::vector copies its contents, so you're actually copying the same object 200 times.

Upvotes: 5

Related Questions