Created
April 13, 2010 11:28
-
-
Save DmitrySoshnikov/364525 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* by Dmitry A. Soshnikov */ | |
#include "stdafx.h" | |
#include <iostream> | |
struct Object { | |
int x; | |
int y; | |
}; | |
// call "by reference" | |
void call_by_reference(Object& oAlias) { | |
oAlias.x = 100; | |
oAlias.y = 200; | |
// but if we assign a new value to oAlias | |
// object outside will be modified also | |
// Object tmp; | |
// tmp.x = 1000; | |
// tmp.y = 2000; | |
// oAlias = tmp; | |
} | |
// call by pointer as a version of "by sharing" | |
void call_by_pointer(Object* oRefCopy) { | |
// change properties, dereferencing the pointer | |
(*oRefCopy).x = 100; | |
// or via convinient "sugar", overloaded "->" operator | |
oRefCopy->y = 200; | |
// bind oRefCopy to the *new* memory block | |
// assigning new address | |
// it can be done also as: | |
// Object tmp; | |
// tmp.x = 1000; | |
// tmp.y = 2000; | |
// oRefCopy = &tmp; | |
oRefCopy = new Object; | |
// the cnages won't touch object outside | |
// because oRefCopy references already other object | |
oRefCopy->x = 1000; | |
oRefCopy->y = 2000; | |
// but if we would dereferenced oRefCopy pointer | |
// and assign a new value to it (and *before* oRefCopy was bound to new address): | |
// (*oRefCopy) = tmp; | |
// then object outside will be changed | |
} | |
using namespace std; | |
int main() | |
{ | |
// test object | |
Object o; | |
o.x = 10; | |
o.y = 20; | |
// --------------call by reference ---------------- | |
// reference (alias) | |
Object& oLocalAlias = o; | |
// before (referencing to o) - 10, 20 | |
cout << oLocalAlias.x << endl << oLocalAlias.y << endl; | |
// call by reference | |
call_by_reference(o); | |
// after: | |
// via o directly - 100, 200 | |
cout << o.x << endl << o.y << endl; | |
// and via reference alias - 100, 200 | |
cout << oLocalAlias.x << endl << oLocalAlias.y << endl; | |
// --------------call by sharing ---------------- | |
// call by sharing (by pointer) - pass copy of address, see & | |
call_by_pointer(&o); | |
// 100, 200 | |
cout << o.x << endl << o.y << endl; | |
// 100, 200 | |
cout << oLocalAlias.x << endl << oLocalAlias.y << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment