mercredi 5 août 2015

Correct way for a class to store an std::vector of std::vector and return the vectors within [duplicate]

This question already has an answer here:

I have a class which has a multidimensional array containing a simple object which just stores a couple of integers. This data will be loaded once and some of the vector within will be returned to other classes for them to use (just reading the data). Each "internal" vector will be really big (thousands of simple objects stored in it).

I'm writing the example code with just the relevant stuff to my question. Code example:

class MyClass
{
private:
    std::vector<std::vector<SimpleObject>> multiData;
}

class MyOtherClass
{
private:
    std::vector<SimpleObject> data;
}

So for example MyClass creates an object of type MyOtherClass and assigns one of the vectors to it, lets say:

MyOtherClass* otherClass = CreateOtherClass();
otherClass->data = this->multiData.at(0);

In this way, if I understand correctly, the whole std::vector will be copied and assigned to otherClass. Wouldn't this cause a performance issue when creating lots of MyOtherClass?

If that is right I thought I could use pointers for the storing the internal std::vectors. Let's say we use an std::shared_ptr.

std::vector<shared_ptr<std::vector<SimpleObject>>> data;

Is this the correct solution? I want to avoid copying the whole std::vector each time since this seems costly and wrong.

Also, if MyClass would later alter the data (only the data in SimpleObject and not the actual length of any of the std::vector) in anyway by using a pointer MyOtherClass would also see this changes, right?

Aucun commentaire:

Enregistrer un commentaire