C++ unique_ptr Usage Guide
unique_ptr is a smart pointer class used to manage ownership of dynamically allocated objects. Unlike traditional raw pointers, unique_ptr automatically releases the object it manages, preventing memory leaks.
The usage of unique_ptr is as follows:
- Create a unique_ptr object: You can use the std::make_unique function to create a unique_ptr object and point it to a dynamically allocated object.
std::unique_ptr<int> ptr = std::make_unique<int>(10);
- Access the object pointed to by the unique_ptr: You can access the object pointed to by the unique_ptr using either the arrow operator or the * operator.
std::cout << *ptr << std::endl;
- Transferring ownership: unique_ptr does not allow copying or assigning operations, but you can use the std::move function to transfer its ownership to another unique_ptr object.
std::unique_ptr<int> ptr2 = std::move(ptr);
- Manually releasing objects: unique_ptr automatically releases the object it manages at the end of its lifetime, but it can also be manually released.
ptr2.reset();
- Customizing deleters using lambda expressions: You can use lambda expressions to customize deleters in order to perform specific operations when releasing objects.
std::unique_ptr<int, std::function<void(int*)>> ptr3(new int(20), [](int* p){ std::cout << "Deleting: " << *p << std::endl; delete p; });