Course Content
C++ Smart Pointers
C++ Smart Pointers
Understanding Pointers
What is a Pointer
You can think of pointers as coordinates. They point us to specific locations in the memory, and allow us to access data stored in those locations.
When you declare a pointer, you create a variable that holds the memory address of another variable. You can create a pointer using *
and &
operators.
pointer
int value = 42; // `p_value` now holds the memory address of `value` int* p_value = &value;
Null Pointers
You can use special keywords used to represent a null pointer null
or nullptr
. A null pointer doesn't point to any valid memory address. It's essentially a pointer with no target.
You can also initialize the integer pointer to null
(or nullptr
). We do this when we don't want to associate the pointer with a specific value right away.
null_pointer
int* p_int = null; // `p_int` is initialized to be null double* p_double = nullptr; // `p_double` is initialized to be null
Reassigning Pointers
Pointers can be reassigned to point to different memory addresses. However, reassigning a pointer without proper management can lead to issues like memory leaks or dangling pointers.
reassigning_pointers
int x = 42; // Create an integer variable and assign a value to it int y = 43; // Create another integer variable int* p_int = &x; // Make the `p_int` variable point to the address of the integer variable `x` p_int = &y; // Reassign the `p_int` variable to `y`
Pointer Arithmetic
Pointer arithmetic is a fascinating aspect of pointers. It allows you to traverse memory by incrementing or decrementing the address held by a pointer.
For example, consider the following code where we create an array of integers and then define a pointer to hold the address of the array. Since an array contains multiple elements, a pointer, by default, stores the address of the first element, which in this case is the integer 1.
pointer_arithmetic
// Defining an array of integers int arr[5] = {1, 2, 3, 4, 5}; // The pointer holds the memory address of the first element in the array int* p_int = arr; // Incrementing the pointer makes the pointer point to the second value p_int = p_int + 1; // Dereference the pointer to get the actual second value int second_element = *p_int; // Equals to `2`
To access the second element, increment the pointer by 1 and then dereference it using the (*
) operator. Dereferencing returns the value stored at the memory address held by the pointer (in this case, the integer 2). Follow the comments in the code to understand each step!
Thanks for your feedback!