For the complete documentation index, see llms.txt. This page is also available as Markdown.

🐽Smarter Pointers

As we've seen, we humans are pretty dumb and inept at managing memory.

Here's where smart pointers come in! They are smarter abstractions introduced in C++11 to help us manage memory automatically.

Unique Pointers

Basics

main.cpp
#include <iostream>
#include <memory>

int main() {
    std::unique_ptr<int> score = std::make_unique<int>(100);
    std::cout << *score << std::endl;
} // automatically deleted here

Semantically, unique pointers convey the idea there is exactly only one owner of the resource being pointed to.

Unique pointers:

  • cannot be copied

  • can be moved

  • are automatically deleted when it goes out of scope

Transferring Ownership

Shared Pointers

Both p1 and p2 point to the same object. Memory for the integer 10 is only free'ed when both p1 and p2 goes out o scope.

Internally, a shared _ptr uses a reference count to track when it shoud deallocate. We can see the live reference count by invoking use_count().

Tackling Our Original Code

Exercise

Given the original code in Memory Painpoints, can you try to use some of these abstractions to create better, memory-safe code?

Answer

Last updated

Was this helpful?