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!
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:
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 containers) may misbehave. One way to combat this is to define an
operator==method for your class (and it may be argued that this is a good idea when overriding the copy constructor even if you don’t use the method), to keep it conceptually ‘sound’ and also as a kind of internal documentation. If your class gets much use, you will likely also end up providing anoperator=so that you can maintain the separation of your automatically generated instance id from class member assignments that should take place under this operator. And so on 😉It might disambiguate the whole issue of ‘different id values for copies’ if you have enough control over the program to use dynamically created instances (via new) and use pointers to those inside containers. This does mean you need to ‘initialise elements “manually”‘ to some degree – but it’s not a lot of work to write a function that gives you back a vector full of pointers to new, initialised instances. If you consistently deal with pointers when using standard containers, you won’t have to worry about the standard containers creating any instances ‘under the covers’.
If you’re aware of all those issues, and believe you can cope with the consequences (which is of course highly dependent on your particular context), then overriding the copy constructor is a viable option. After all, the language feature is there for a reason. Obviously, it is not as simple as it looks, and you should be careful.