[c++] std::unique_ptr

In C++, std::unique_ptr is a smart pointer that ensures that only one pointer can point to a resource at any given time. It is part of the C++11 standard and is a safer and more efficient alternative to raw pointers.

Key features of std::unique_ptr

Example usage

The following example demonstrates the basic usage of std::unique_ptr:

#include <iostream>
#include <memory>

int main() {
    std::unique_ptr<int> p1(new int(5));
    std::cout << "Value: " << *p1 << std::endl;

    // p1 automatically releases the memory when it goes out of scope
    return 0;
}

In this example, p1 is initialized with a dynamically allocated integer and automatically releases the memory when it goes out of scope.

Benefits of using std::unique_ptr

std::unique_ptr is a powerful tool for managing dynamic memory allocation in C++ while ensuring safety and efficiency.

For more details, refer to the C++ reference documentation for std::unique_ptr.


By using std::unique_ptr, C++ developers can easily manage memory allocation and deallocation, reducing the risk of memory leaks and pointer-related bugs. Its strong ownership semantics and automatic memory management make it a valuable tool for modern C++ programming.