Learning Hub Search Ctrl K

Legacy C++ › 2. Pointers, References and Memory

Pointers and References

How pointers and references name objects indirectly, and when to choose each.

beginner #pointers#references#memory

Explanation

A pointer is an object that stores the address of another object. A reference is an alias: another name for an existing object.

Pointer Reference
Can be null yes no
Can be reseated yes no (bound once)
Must be initialized no yes
Syntax to use the target *p, p->x just the name

Example

#include <iostream>

void incrementByPointer(int* p)  { if (p) ++*p; }
void incrementByReference(int& r) { ++r; }

int main() {
    int n = 5;
    incrementByPointer(&n);     // n == 6
    incrementByReference(n);    // n == 7
    std::cout << n << "\n";

    int* heap = new int(42);    // C++98: you own this memory
    std::cout << *heap << "\n";
    delete heap;                // forgetting this leaks
    heap = 0;                   // no nullptr before C++11
    return 0;
}

Common pitfalls

  • Dangling pointers: using a pointer after delete, or returning the address of a local variable.
  • Leaks: every new needs exactly one delete (and new[] needs delete[]).
  • NULL is just 0: before C++11 there is no nullptr, so overload resolution between int and pointer can surprise you.
  • Prefer a const T& parameter for read-only access to large objects.

Legacy vs modern

C++11 adds nullptr and smart pointers (unique_ptr, shared_ptr) so raw owning pointers are rarely needed. See Move Semantics and unique_ptr.

Exercises

1. Write swap(int&, int&) and a pointer-based version.
void swapRef(int& a, int& b) { int t = a; a = b; b = t; }
void swapPtr(int* a, int* b) { int t = *a; *a = *b; *b = t; }
2. What is wrong with int& f() { int x = 1; return x; }?

It returns a reference to a local that is destroyed when f returns: a dangling reference.