Skip to content

Smart pointers

Smart pointers

Use smart pointers instead of raw pointer whenever possible:

  • But you can't do it without understanding raw pointers
  • Recur to raw non-owning pointers if they are needed

In general, use:

1) No pointers at all

2) Raw non-owning pointers or references if they are needed

3) Smart pointers IF owning pointers can not be averted

4) Owning raw pointers if you know exactly what you are doing and need them (e.g. interfacing with C code).

There are 2 important types of smart pointers:

  • Unique pointer:
    • Only one pointer can point to an address
    • Deletes data automatically when the pointer is destroyed
  • Shared pointer:
    • More than one pointer can point to the same address
    • Deletes data automatically when the last pointer is destroyed
    • More expensive than unique pointers
1
2
3
4
5
6
7
// Only one unique pointer can point to an address
std::unique_ptr<int> c;
if (c) {
    std::cout << "*c : " << *c << '\n';
} else {
    std::cout << "c is empty" << '\n';
}

1
2
3
4
5
6
7
// Previous value is deleted if needed
c = std::make_unique<int>(2);
if (c) {
    std::cout << "*c : " << *c << '\n';
} else {
    std::cout << "c is empty" << '\n';
}

1
auto c2 = std::make_unique<int>(3);

1
2
3
// Swapping values is valid
c.swap(c2);
// c = c2; <- but copying doesn't work

1
2
3
4
5
6
c = std::move(c2);
if (c) {
    std::cout << "New *c : " << *c << '\n';
} else {
    std::cout << "c is empty" << '\n';
}

1
2
3
4
5
6
auto sp = std::make_shared<int>(2);
if (sp) {
    std::cout << "New *sp : " << *sp << '\n';
} else {
    std::cout << "sp is empty" << '\n';
}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
std::shared_ptr<int> sp2 = sp;
*sp2 = 3;
if (sp) {
    std::cout << "New *sp : " << *sp << '\n'; // 3
} else {
    std::cout << "sp is empty" << '\n';
}
if (sp2) {
    std::cout << "New *sp2 : " << *sp << '\n'; // 3
} else {
    std::cout << "sp2 is empty" << '\n';
}

//[count Count number of shared pointers
// How many pointers are pointing to this number?
std::cout << "There are " << sp.use_count() << " pointers to " << sp.get()
          << '\n';

1
2
3
// How many pointers are pointing to this number?
std::cout << "There are " << sp.use_count() << " pointers to " << sp.get()
          << '\n';

Share Snippets