Skip to content

References

References

  • They solve some problems with raw pointers
  • Once initialized, a reference cannot be changed. This makes them less dangerous.
  • Instead of "pointing" to an address, a reference only "refers" to a fixed address / variable
1
2
3
4
int n = 1;
int &r1 = n;
int &r2 = r1;
int &r3 = n;

1
2
3
4
std::cout << "n: " << n << '\n';
std::cout << "r1: " << r1 << '\n';
std::cout << "r2: " << r2 << '\n';
std::cout << "r3: " << r3 << '\n';

1
2
int ar[3];
int(&ra)[3] = ar;

1
2
std::cout << "ar: " << ar << '\n';
std::cout << "ra: " << ra << '\n';

1
2
int *p = new int(3);
int *&ppr = p;

1
2
std::cout << "ar: " << ar << '\n';
std::cout << "ra: " << ra << '\n';

1
2
int &prr = *p;
std::cout << "prr: " << prr << '\n';

1
2
delete p;
// ppr and prr are now dangling references

Share Snippets