9 Making a good point – Pointers at work

 

This chapter covers

  • Understanding what pointers are and why they matter.
  • Learning how to access and manipulate the values stored in pointers through dereferencing.
  • Understanding the relation of dynamic memory allocation and pointers.
  • Discovering how pointers work with arrays and functions.
  • Exploring smart pointers and the way they handle memory for us.

In this chapter, we will learn about pointers, which are variables that store the memory addresses of other objects. Pointers play a crucial role in managing memory, and allow us to work with dynamic data structures and objects. The concept of pointers can be confusing and demanding, and in this chapter, we explore pointers step by step so you can gain confidence with ease.

We start this chapter with raw pointers, which provide direct access to memory addresses, allowing us to allocate and deallocate memory manually. We'll learn how to create, assign, and manipulate raw pointers, as well as their associated risks and challenges. You will understand the relationship between pointers and dynamic memory allocation.

Next, we explore smart pointers, which are like intelligent wrappers around raw pointers, that provide automatic memory management. We'll explore the different types of smart pointers, and understand their distinct characteristics, use cases, and the benefits they bring to our code.

9.1 To the point – the concept of pointers

9.1.1 Good points for using pointers

9.1.2 What’s your point? Declaring pointers

9.1.3 Address it – how to initialize pointers

9.1.4 nullptr: The zero-drama pointer initialization

9.2 Raw nerves: Raw pointers and dynamic memory allocation

9.2.1 The “new” kid in the block

9.3 The quirks of pointers and arrays

9.3.1 2D arrays and pointers can fly

9.3.2 The pluses and the minuses of pointer’s arithmetic (in the literal sense)

9.3.3 Straight as an arrow: The -> operator

9.3.4 Code exercise: Manage the tenants in an apartment building.

9.3.5 Change me not – working with const pointers

9.4 Pointers in the functions’ playground

9.4.1 References vs. Pointers

9.4.2 Return a pointer from a function

9.4.3 Passing a pointer to a function as a parameter to another function

9.5 The C++ smart cookies: Smart pointers at work

9.5.1 Stay unique: using the std::unique_ptr

9.6 Final exercise: write a Snakes and Ladders game

9.6.1 <chrono> - pseudo-random turns ‘randomlicious’

9.7 summary