Created
June 17, 2014 23:41
-
-
Save FlyingJester/fa25425a0a91fc902dd8 to your computer and use it in GitHub Desktop.
Example of using a reference to a pointer.
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
| #include <cstdio> | |
| using namespace std; | |
| typedef int *ip_t; | |
| ///// | |
| // A class that holds a reference to a pointer. | |
| class PointerHolder { | |
| ip_t &m; | |
| public: | |
| PointerHolder(ip_t &a) | |
| : m(a) //Initialize the ref with a pointer. | |
| {} | |
| void ModifyPointer(ip_t a){ | |
| m=a; // Modify via this object's reference. | |
| } | |
| ip_t GetPointer(void){ | |
| return m; | |
| } | |
| }; | |
| int main() | |
| { | |
| int *point = new int(); | |
| *point = 312; | |
| printf("Point is at addr %p, and contains %i\n", point, *point); | |
| PointerHolder *holder = new PointerHolder(point); | |
| printf("Holder holds %p inside it\n", holder->GetPointer()); | |
| int *newpoint = new int(); | |
| *newpoint = 216; | |
| printf("NewPoint is at addr %p, and contains %i\n", newpoint, *newpoint); | |
| printf("Changing Holder to hold NewPoint.\n"); | |
| holder->ModifyPointer(newpoint); | |
| ///// | |
| // Will `point' have changed to reflect `holder'? | |
| printf("Point is at addr %p, and contains %i\n", point, *point); | |
| printf("Holder holds %p inside it\n", holder->GetPointer()); | |
| ///// | |
| // `point' should have changed to be identical to `newpoint', and we only touched `holder'! | |
| return 0; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Compiling the source code....
g++ RefPexample.cpp -o demo -lm -pthread -lgmpxx -lgmp -lreadline 2>&1Executing the program....
./RefPexamplePoint is at addr 0x602010, and contains 312
Holder holds 0x602010 inside it
NewPoint is at addr 0x602050, and contains 216
Changing Holder to hold NewPoint.
Point is at addr 0x602050, and contains 216
Holder holds 0x602050 inside it