int byRef(A& v){ v = A(3); return 0; }
This causes the temporary object to be assigned to the object passed by reference, the object used in the function call changes. A shallow copy will be executed if no assignment operator is assigned.
int byP (A* v){ v = &A(4);
This copies the pointer to a temporary object to the passed value of the pointer. The destination function is called. The value of 'v' changes, but object v indicates that the address of the object passed as an argument does not change.
If you have done this:
struct A { int x; A(int v){ x = v; } A &operator = (A &rhs){ cout << "assignment!"; } };
then the "assignment" will be displayed in the byRef function, but not in the byP function.
Although & is implemented using pointers under the hood, as others have said, they are treated as an object passed to the function by the language.
So, to implement byRef with pointers:
int byRefUsingP (A *v) { *v = A(3);
Skizz source share