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.
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.
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 is straightforward. You can create a unique_ptr from a raw pointer and delete it when the unique_ptr goes out of scope.
#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;
}You can access the underlying raw pointer using the .get() method.
int* rawPtr = myUniqueInt.get();You can reset the pointer by assigning a new pointer.
myUniqueInt.reset(new int(10)); // myUniqueInt now owns a new int with value 10You can swap the ownership of two unique_ptr objects.
std::unique_ptr<int> myUniqueInt1(new int(42));
std::unique_ptr<int> myUniqueInt2(new int(10));
std::swap(myUniqueInt1, myUniqueInt2);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.
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 thrownWhat 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! šÆ