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 and delete 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 not utility
  • std::unique_ptr accepts the raw pointer of an object of type T. In other words, it accepts T*
  • 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>
std::unique_ptr<int> ptr = std::make_unique<int>(42);
  • 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 example

#include <memory>
struct Base {};
struct Derived : Base {};
 
int main() {
   std::unique_ptr<Base> base_ptr = std::make_unique<Derived>();
}

When base_ptr goes out of scope, the Base unique pointer will attempt to delete the Derived class object (static type) and Base (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();