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.
std::weak_ptr<Person> weakPointer : lets you look at a shared_ptr without incrementing the ref count.
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 addressint*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(newPerson());//bad old way to init// reset pointer to a new person objectuniquePointerToPerson.reset(newPerson());// otherPointerToPerson now holds the unique pointerstd::unique_ptr<Person>otherPointerToPerson=std::move(uniquePointerToPerson);// reset to nullptrotherPointerToPerson.reset();// creating new unique pointer to new PersonotherPointerToPerson=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(newPerson());//bad old way to init// decrement reference count, makes it 0sharedPointerToPerson.reset();// increment the reference count by creating new PersonsharedPointerToPerson=std::make_shared<Person>();// better new way to init