Alex Rivera | Logout

How to call constructor of objects contained in a std::vector?

Asked 2010-07-17T16:36:52.180
11

When I create a std::vector of objects, the constructor of these objects is not always called.

#include <iostream>
#include <vector>
using namespace std;

struct C {
    int id;
    static int n;
    C() { id = n++; }   // not called
//  C() { id = 3; }     // ok, called
};

int C::n = 0;


int main()
{
    vector<C> vc;

    vc.resize(10);

    cout << "C::n = " << C::n << endl;

    for(int i = 0; i < vc.size(); ++i)
        cout << i << ": " << vc[i].id << endl;  
}

This is the output I get:

C::n = 1
0: 0
1: 0
2: 0
...

This is what I would like:

C::n = 10
0: 0
1: 1
2: 2
...

In this example, am I forced to resize the vector and then initialise its elements "manually"?
Could the reason be that the elements of a vector are not initialised in an ordered way, from the first to the last, and so I cannot obtain a deterministic behaviour?

What I would like to do, is to easily count the number of objects created in a program, in different containers, in different points of the code, and to give a single id to each of them.

Thank's!

Edit
Report

1 Answer

5

The reason is that vector::resize inserts copies by calling the automatically provided copy constructor, rather than the constructors you have defined in your example.

In order to get the output you want, you can define the copy constructor explicitly:

struct C {
//....
C(const C& other) {
    id = n++;
    // copy other data members
}
//....
};

Because of the way vector::resize works though (it has a second optional argument used as a 'prototype' for the copies it creates, with a default value in your case of C()), this creates 11 objects in your example (the 'prototype' and 10 copies of it).

Edit (to include some of the good advice in the many comments):

There are several downsides to this solution worth noting, as well as some options and variants that are likely to yield more maintainable and sensible code.

  • This method does add maintenance costs, and an amount of risk. You have to remember to modify your copy constructor whenever you add or remove members variables of the class. You don't have to do that if you rely on the default copy constructor. One way to combat this problem is to encapsulate the counter in another class (like this), which is also arguably better OO design, but then of course you also have to keep in mind the many issues that can crop up with multiple inheritance.

  • It can make it harder for other people to understand, because a copy is no longer exactly what most people would expect. Similarly, other code that deals with your classes (including the standard conta

answered 2010-07-17T16:42:50.690

Your Answer