mercredi 22 avril 2015

How to force reserve() to use a non-default constructor?

Suppose we have the following code snippet:

MyType::MyType();            // size of MyType.aMember is a default size
MyType::MyType(int mySize);  // size of MyType.aMember depends on mySize
...
...
std::vector<MyType> myTypeVector;
myTypeVector.reserve(numberOfObjects);  // memory reserved is numberOfObjects * sizeof(MyType)
...

How can one make reserve not use the default constructor to determine the size of the individual objects, but use a desired constructor instead?

One can try the following:

MyType::MyType();            // size of MyType.aMember is a default size
MyType::MyType(int mySize);  // size of MyType.aMember depends on mySize
...
...
std::vector<MyType> myTypeVector(numberOfObjects, MyType(desiredSize));  // memory allocated is numberOfObjects * sizeof(MyType(desiredSize))
...

But the above calls the copy constructor which I would like to avoid for efficiency reasons. Hence my question.

Aucun commentaire:

Enregistrer un commentaire