Tuesday, April 7, 2015

Overview

In C++, pointers are extremely important. This is only a brief overview of pointers. You can find more information about pointers here. To read about the differences between a shared and unique pointer, refer to this post.

Content

There are several types of pointers now in C++11 that you should at least know exist.

  1. Person* normalPointer : normal pointer
  2. std::shared_ptr<Person> sharedPointer : reference counted smart pointer.
  3. std::weak_ptr<Person> weakPointer : lets you look at a shared_ptr without incrementing the ref count.
  4. std::unique_ptr<Person> uniquePointer : is unique, have to use std::move to change variable.

Normal Pointer

1
2
3
4
5
6
7
8
9
10
// pointerToA points to A's memory address
int* pointerToA = &A;
Person* pointerToP = &P;

// to access `A`'s content, you dereference the pointer
*pointerToA = 5; // now A = *pointerToA = 5

// to access `P`'s methods, you can use the -> notation or (*P)
(*pointerToP).pMethod();
pointerToP->pMethod();

Unique Pointer in C++11

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <memory>
std::unique_ptr<Person> uniquePointerToPerson(new Person()); //bad old way to init

// reset pointer to a new person object
uniquePointerToPerson.reset(new Person());

// otherPointerToPerson now holds the unique pointer
std::unique_ptr<Person> otherPointerToPerson = std::move(uniquePointerToPerson);

// reset to nullptr
otherPointerToPerson.reset();

// creating new unique pointer to new Person
otherPointerToPerson = std::make_unique<Person>(); // better new way to init

Shared Pointer in C++11

1
2
3
4
5
6
7
8
9
// uses reference counting
#include <memory>
std::shared_ptr<Person> sharedPointerToPerson(new Person()); //bad old way to init

// decrement reference count, makes it 0
sharedPointerToPerson.reset();

// increment the reference count by creating new Person
sharedPointerToPerson = std::make_shared<Person>(); // better new way to init

Random Posts