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)

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
- 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_ptr
s and/or weak_ptr
s 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
- read-only access to objects
- 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_; } int right () const { return this->r_; } … IntRange& shift (int by) { l_ += by; r_ += by; return *this; } IntRange& widen (int by) { l_ -= by; r_ += by; return *this; } };
|
IntRange r1 {1,3}; r1.shift(1); r1.shift(2).widen(1);
|
References
https://hackingcpp.com/cpp/lang/pointers.html