Unique Pointer
A unique pointer is a type of smart pointer that owns and manages an object. When
std::unique_ptr
goes out of scope, it deletes the object it is pointing to. In essence, smart pointers model object ownership, a similar concept in Rust Programming
- It is safer and more efficient to use than
new
anddelete
in C++. It would be useful in applications that require memory safety and clean management of allocated memory for objects - It belongs to
<memory>
and notutility
std::unique_ptr
accepts the raw pointer of an object of typeT
. In other words, it acceptsT*
- You cannot have two different unique pointers encapsulating the same object. It violates the semantics of a unique pointer
- The best approach for creating a unique pointer is by using
make_unique<T>
- The advantage is that I don’t have to remember to use
delete
to deallocate the pointer once it’s done. The unique pointer will automatically handle that!
Problems with
unique_ptr
unique_ptr
allows implicit conversions that are actually unsafe. For exampleWhen
base_ptr
goes out of scope, theBase
unique pointer will attempt to delete theDerived
class object (static type) andBase
(dynamic type).Base
does not have a destructor defined, which results in issues. Using virtual destructors can help solve the issue
I came across this post on Stack Overflow while finding a resource to understand what unique pointers are, and the code in the question seemed odd
#include <utility> //declarations of unique_ptr
using std::unique_ptr;
// default construction
unique_ptr<int> up; //creates an empty object
// initialize with an argument
unique_ptr<int> uptr (new int(3));
double *pd= new double;
unique_ptr<double> uptr2 (pd);
// overloaded * and ->
*uptr2 = 23.5;
unique_ptr<std::string> ups (new std::string("hello"));
int len=ups->size();