Hello,
I have one easy question:
class A {
private:
int _number;
vector<A> Vector;
public:
A(int n) { _number = n; }
A() {}
void addCopy(A a) { Vector.push_back(a); }
void addReference(A* a) {
Vector.push_back(*a);
}
};
int main (int argc, char** argv) {
A aa;
A bb(99);
aa.addCopy(bb);
aa.addReference(&bb);
return EXIT_SUCCESS;
}
class A {
private:
int _number;
vector<A> Vector;
public:
A(int n) { _number = n; }
A() {}
void addCopy(A a) { Vector.push_back(a); }
void addReference(A* a) {
Vector.push_back(*a);
}
};
int main (int argc, char** argv) {
A aa;
A bb(99);
aa.addCopy(bb);
aa.addReference(&bb);
return EXIT_SUCCESS;
}
To copy to clipboard, switch view to plain text mode
In this case, A keep a vector and when push_back() is called, it makes a copy; Then regarding addCopy: 1. pass bb to add (and it makes one copy of bb); 2. push a into Vector (and make one other copy). With referenceCopy instead I can avoid overhead of passing bb to the add() (and if bb it's large it can enhance the performance). With this above I wonder: why should I pass an objects (e.g. A) as value? I'm thinking that It's better pass an object always by reference (IF I DON'T CHANGE IT INSIDE THE FUNCTION, like I do in this case)
Is this above right?
thanks
Bookmarks