i am new to c++ and often have the problem to create list of objects from file data. Since the amount of data may be huge i want to avoid unnecessary copying.
class Tool
{
Tool(string fileName);
vector<MyClass> read(); // 1)
vector<MyClass*> read(); // 2)
read(vector<MyClass*>& vec); // 3)
}
vector<MyClass> Tool::read()
{
MyClass c;
vector<MyClass> vec;
c.a = 1;
c.b = 2;
vec.push_back(c);
c.a = 3;
c.b = 4;
vec.push_back(c);
...
return vec;
}
vector<MyClass*> Tool::read()
{
MyClass* c;
vector<MyClass> vec;
c = new MyClass();
c->a = 1;
c->b = 2;
vec.push_back(c);
c = new MyClass();
c->a = 3;
c->b = 4;
vec.push_back(c);
...
return vec;
}
Tool::read(vector<MyClass*>& vec)
{
MyClass* c;
c = new MyClass();
c->a = 1;
c->b = 2;
vec.push_back(c);
c = new MyClass();
c->a = 3;
c->b = 4;
vec.push_back(c);
...
return vec;
}
In 1) the read will be quite expensive because there is much to copy. I have read somewhere that recent c++ versions could make those copies quite efficient but i am not sure
In 2) the copy operations should use significant less data. But I have to delete somewhere and at some time the objects where the pointers are pointing to. I guess i need to do that somewhere outside of Tool, since i don't need Tool anymore after read the file.
In 3) I can give the pointer to the read method and be able to push the pointers directly into the destination vector. Seem to be the best way out of the ways getting my vector of MyClasses. And since i give the vector to the read method I am more aware of deleting its elements later.
Maybe someone knows better ways to deal with such scenarios?
Thanks much for comments and help.
Edit1: I added implementations as UnholySheep suggested.
I did something interesting:
Notice that the address of the vector is the same both inside makeVec and then inside main(). This is because the compiler optimizes what is going on.
But then I changed main:
Running this version:
So... from this, if you're returning an object of any type, then if you can do both declaration and instantiation together, it's more efficient. Do this:
Do NOT do this: