OK. So I performed some research. I just have tested four solutions. Results are presented in the table below: (I can't put an image, please click the link)
Comparing an efficiency of list and vector containers
As you can see from the table, vector containing objects is the fastest solution. It is also true that storing pointers to objects is much slower than containing real objects.
SUMMARY:
- Sequential access to objects aggregated in list is slow, probably because it requires "jumping" from pointer to pointer and particular objects don't have to be stored in consecutive memory cells
- Sequential access to vector is fast, probably because objects are stored in linear, consecutive memory cells
- Using iterator to access consecutive objects is faster than using indexes, what isn't surprising
- Storing pointers instead of real objects is much slower, especially during allocation and deallocation of container (heap allocation)
- Independently from storing object type, deallocation of list is much slower than deallocating of vector
Answering to question asked by @Emile Cormier - Why I would like to use pointer to container? This ensure me an access to vector/list elements even after deletion of parent class object. Please consider this part of code:
class A{
public:
A(){
this->test = new vector<int>;
for(int i = 0; i < 10; i++){
test->push_back(i);
}
}
~A(){
cout << "object A is dead\n";
test->clear(); // <--- COMMENTING this line allows to access to the vector's elements "after death" without copying
}
vector<int>* GetPointer(){
return this->test;
}
private:
vector<int>* test;
};
class B{
public:
B(){
for(int i = 0; i < 10; i++){
test.push_back(i);
}
}
~B(){
cout << "object B is dead\n";
test.clear();
}
vector<int> GetbyValue(){
return test;
}
private:
vector<int> test;
};
cout << "\nCASE A\n";
A* instance = new A();
vector<int>* local = instance->GetPointer();
delete instance; //deletion before calling!!!
//Access is impossible, because clear method in destructor destroys original vector, connected with pointer
cout << "Printing A\n";
for(int i = 0; i < local->size(); i++){
cout << (*local)[i] << "\n";
}
cout << "\nCASE B\n";
B* instance2 = new B();
vector<int> local2 = instance2->GetbyValue();
delete instance2; //deletion before calling!!!
//Access is still possible, because vector has been copied to local variable
cout << "Printing B\n";
for(int i = 0; i < local2.size(); i++){
cout << (local2)[i] << "\n";
}
cout << "THE END\n";
When I don't use a pointer to vector (case B), I although can access objects from vector after deletion of "B" class object BUT in reality I use a local copy of returned vector. Using a pointer to vector (case A) allows me to get an access to vector objects even after deletion of "A" class object, when I don't call clear() method in destructor manually of course.
Finally - thanks everyone for help. I think that my problem has been solved.