dimanche 16 juillet 2017

How do I dynamically allocate an array of objects in C++ with individual constructor parametes for each object?

Let's assume that I have a class

class Foo
{
public:
    Foo (const std::string&);
    virtual ~Foo()=default;
private:
    //some private properties
};

and I want to create many instances of this class. Since I aim for good performance, I want to allocate the memory at once for all of them (at this point, I know the exact number but only at runtime). However, each object shall be constructed with an individual constructor parameter from a vector of parameters

std::vector<std::string> parameters;

Question: How can this be achieved?

My first try was to start with a std::vector<Foo> and then reserve(parameters.size()) and use emplace_back(...) in a loop. However I cannot use this approach because I use pointers to the individual objects and want to be sure that they are not moved to a different location in memory by the internal methods of std::vector. To avoid this I tried to delete the copy constructor of Foo to be sure at compile time that no methods can be called that might copy the objects to a different location but then I cannot use emplace_back(...) anymore. The reason is that in this method, the vector might want to grow and copy all the elements to the new location, it does not know that I reserved enogh space.

Aucun commentaire:

Enregistrer un commentaire