Pointers

Pointer to Object of Type T

  • stores a memory address of an object of type T
  • can be used to inspect/observe/modify the target object
  • can be redirected to a different target (unlike references)
  • may also point to no object at all (be a Null Pointer)

pointer to object c.png

Raw Pointers: T*

  • essentially an (unsigned) integer variable storing a memory address
  • size: 64 bits on 64 bit platforms
  • many raw pointers can point to the same address / object
  • lifetimes of pointer and taget (pointed-to) object are independent

Smart Pointers C++11

std::unique_pointer<T>
  • used to access dynamic storage, i.e., objects on the heap
  • only one unique_ptr per object
  • pointer and target object have same lifetime
std::shared_pointer<T>
std::weak_pointer<T>
  • used to access dynamic storage, i.e., objects on the heap
  • many shared_ptrs and/or weak_ptrs per object
  • target object lives as long as at least one shared_ptr points to it

nullptr C++11

  • special pointer value
  • is implicitly convertible to false
  • not necessarily represented by 0 in memory! (depends on platform)

Coding Convention: nullptr signifies “value not available”

  • set pointer to nullptr or valid address on initialization
  • check if not nullptr before dereferencing

const and Pointers

Purposes

  1. read-only access to objects
  2. preventing pointer redirection

Syntax

pointer to type T pointed-to value modifiable pointer itself modifiable
T *
T const *
T * const
T const * const

👉 Read it right to left: “(const) pointer to a (const) T”

The “this” Pointer

  • available inside member functions
  • this returns the address of an object itself
  • this-> can be used to access members
  • *this accesses the object itself
class IntRange {
int l_ = 0;
int r_ = 0;
public:
explicit
IntRange (int l, int r): l_{l}, r_{r} {
if (l_ > r_) std::swap(l_, r_);
}
int left () const { return l_; }
// can also use 'this' to access members:
int right () const { return this->r_; }

// returns reference to object itself
IntRange& shift (int by) {
l_ += by;
r_ += by;
return *this;
}
IntRange& widen (int by) {
l_ -= by;
r_ += by;
return *this;
}
};
IntRange r1 {1,3}; // 1 3
r1.shift(1); // 2 4
r1.shift(2).widen(1); // 3 7 chaining possible!

References

https://hackingcpp.com/cpp/lang/pointers.html