capypad
0 day streak
cpp / intermediate
Snippet

Smart Pointers: std::unique_ptr

std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. It cannot be copied, only moved, ensuring strict single ownership.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
#include <memory>
#include <iostream>
 
void example() {
// Creating a unique_ptr to an integer
std::unique_ptr<int> ptr = std::make_unique<int>(42);
if (ptr) {
std::cout << "Value: " << *ptr << std::endl;
}
} // ptr is automatically destroyed here, and memory is freed
Breakdown
1
std::unique_ptr<int> ptr = std::make_unique<int>(42);
Allocates an integer on the heap and wraps it in a unique_ptr for automatic management.
2
std::cout << *ptr
Dereferences the smart pointer just like a raw pointer to access the stored value.