PDA

View Full Version : passing an object



mickey
15th January 2008, 12:42
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;
}


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

jacek
15th January 2008, 21:51
You can pass by value if copying is cheap (for example you want to pass an integer or char) or when you know that you have to make a copy anyway. Otherwise passing by reference is cheaper.

mickey
16th January 2008, 10:16
yes, but suppose to have a program larger than 100 000 lines of code where I could have many function that pass one char or int; if I did all by value (suppose even in those case by value or by reference has no difference) isn't it bad?

jpn
16th January 2008, 10:27
Passing a primitive data type (char, short, int, long, enum...) by value costs the same as passing it by reference.