C++ unique_ptr (C++11) šŸŽÆ

beginner
8 min

C++ unique_ptr (C++11) šŸŽÆ

Welcome to our guide on C++'s unique_ptr! In this lesson, we'll dive into this powerful smart pointer, introduced in C++11, and learn how to use it effectively in your projects.

What is a Smart Pointer? šŸ“

Before we dive into unique_ptr, let's first understand what a smart pointer is. In C++, a smart pointer is a class that acts like a regular pointer but with additional capabilities to manage memory automatically. This helps prevent common memory-related bugs like memory leaks and double-deletion.

Introducing unique_ptr šŸ’”

unique_ptr is a type of smart pointer that represents an owner of a heap-allocated object. It ensures that the managed object is deleted exactly once when it's no longer needed, and no other unique_ptr can own the same object.

Creating a unique_ptr šŸ“

Creating a unique_ptr is straightforward. You can create a unique_ptr from a raw pointer and delete it when the unique_ptr goes out of scope.

cpp
#include <memory> int main() { int* myInt = new int(42); std::unique_ptr<int> myUniqueInt(myInt); // myUniqueInt now owns myInt // myInt is no longer accessible // ... use myUniqueInt ... return 0; }

unique_ptr Operations šŸ’”

Accessing the underlying pointer

You can access the underlying raw pointer using the .get() method.

cpp
int* rawPtr = myUniqueInt.get();

Resetting the pointer

You can reset the pointer by assigning a new pointer.

cpp
myUniqueInt.reset(new int(10)); // myUniqueInt now owns a new int with value 10

Swapping pointers

You can swap the ownership of two unique_ptr objects.

cpp
std::unique_ptr<int> myUniqueInt1(new int(42)); std::unique_ptr<int> myUniqueInt2(new int(10)); std::swap(myUniqueInt1, myUniqueInt2);

Destruction and Exception Safety šŸ’”

When a unique_ptr goes out of scope, its managed memory is automatically deleted. This makes it exception-safe, as the destructor doesn't throw exceptions.

cpp
std::unique_ptr<int> myUniqueInt(new int(42)); try { // some exception-throwing code... } catch (...) { // ... exception handling code ... } // myUniqueInt is automatically deleted here, even if an exception was thrown

Quiz šŸ’”

Quick Quiz
Question 1 of 1

What does a `unique_ptr` ensure about the managed object?

By learning unique_ptr, you're taking a step forward in mastering C++. In the next lesson, we'll explore another powerful smart pointer: shared_ptr. Stay tuned! šŸŽ‰

Remember, practice is key to mastery. Try implementing unique_ptr in your projects and experiment with its various features. Happy coding! šŸŽÆ