si***************@gmail.com wrote:
I would like to create a Class which has a list of another class as it
attribute.
I wonder, should I do this:
class B {
private:
vector<A> _listOfA;
Provided the compiler knows what 'A' is and what 'vector' is. Also,
consider that naming a _vector_ "list" is potentially confusing.
}
;
B::B() {
A a1;
A a2;
_listOfA.push_back(a1);
_listOfA.push_back(a2);
}
or this:
class B {
private:
vector<A*> _listOfA;
}
;
B::B() {
A* a1 = new A();
A* a2 = new A();
_listOfA.push_back(a1);
_listOfA.push_back(a2);
}
I think #1 is the preferred way in C++. But isn't there is a
performance penalty in #1?
Performance penalty is unrecognisable until the program is complete and
can be run to collect performance data (like under a profiler, for
example).
(when you push_back(a1), you are copying a1 to the list of A, right? So
should we do #2, which is pass by reference instead of pass by value?
Right, you're copying a1. If copying is expensive, storing pointers can
be a better approach. (BTW, in #2 you're copying 'a1' as well, but it is
merely a pointer, so copying of a pointer is usually cheap). Given the
minuscule amount of code you posted, it's impossible to conclude one way
or the other.
Keep in mind that storing pointers obtained from 'new' requires cleaning
them up at the time when they are not needed any longer (in the d-tor, for
example). You've not shown how or where that is done. If it's not done,
you have a "memory leak".
V