Pass by Reference / Value in C++ -
i clarify differences between value , reference.
i drew picture
so, passing value,
a copy of identical object created different reference, , local variable assigned new reference, point new copy
how understand words: " if function modifies value, modifications appear within scope of calling function both passing value , reference "
thanks!
i think confusion generated not communicating meant passed reference. when people pass reference mean not argument itself, rather the object being referenced. other pass reference means object can't changed in callee. example:
struct object { int i; }; void sample(object* o) { // 1 o->i++; } void sample(object const& o) { // 2 // nothing useful here :) } void sample(object & o) { // 3 o.i++; } void sample1(object o) { // 4 o.i++; } int main() { object obj = { 10 }; object const obj_c = { 10 }; sample(&obj); // calls 1 sample(obj) // calls 3 sample(obj_c); // calls 2 sample1(obj); // calls 4 }
some people claim 1 , 3 pass reference, while 2 pass value. group of people last pass reference, because object not copied.
i draw definition of here claim pass reference. general overview on can found here: difference between pass reference , pass value . first , last pass reference:
sample(&obj); // yields `object*`. passes *pointer* object value. // caller can change pointer (the parameter), // won't change temporary pointer created on call side (the argument). sample(obj) // passes object *reference*. denotes object itself. callee // has got reference parameter. sample(obj_c); // passes *by reference*. reference parameter references // same object argument expression. sample1(obj); // pass value. parameter object denotes different object // 1 passed in.
i vote following definition:
an argument (1.3.1) passed reference if , if corresponding parameter of function that's called has reference type and reference parameter binds directly argument expression (8.5.3/4). in other cases, have pass value.
that means following pass value:
void f1(object const& o); f1(object()); // 1 void f2(int const& i); f2(42); // 2 void f3(object o); f3(object()); // 3 object o1; f3(o1); // 4 void f4(object *o); object o1; f4(&o1); // 5
1
pass value, because it's not directly bound. implementation may copy temporary , bind temporary reference. 2
pass value, because implementation initializes temporary of literal , binds reference. 3
pass value, because parameter has not reference type. 4
pass value same reason. 5
pass value because parameter has not got reference type. following cases pass reference (by rules of 8.5.3/4 , others):
void f1(object *& op); object a; object *op1 = &a; f1(op1); // 1 void f2(object const& op); object b; f2(b); // 2 struct { }; struct b { operator a&() { static a; return a; } }; void f3(a &); b b; f3(b); // passes static reference
Comments
Post a Comment