Skip to content

Instantly share code, notes, and snippets.

@FlyingJester
Created June 17, 2014 23:41
Show Gist options
  • Select an option

  • Save FlyingJester/fa25425a0a91fc902dd8 to your computer and use it in GitHub Desktop.

Select an option

Save FlyingJester/fa25425a0a91fc902dd8 to your computer and use it in GitHub Desktop.
Example of using a reference to a pointer.
#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;
}
@FlyingJester
Copy link
Copy Markdown
Author

Compiling the source code....
g++ RefPexample.cpp -o demo -lm -pthread -lgmpxx -lgmp -lreadline 2>&1

Executing the program....
./RefPexample

Point 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment