Sobes.tech
Junior — Middle

What are the differences between a standard non-smart pointer and the std::unique_ptr smart pointer in C++?

sobes.tech AI

Answer from AI

Main differences between a standard raw pointer and the smart pointer std::unique_ptr in C++:

  • Lifetime management of the object:

    • Raw pointer simply stores the address but does not manage the object's lifetime. You need to manually call delete.
    • std::unique_ptr automatically deletes the object when it goes out of scope, preventing memory leaks.
  • Ownership:

    • Raw pointer does not own the object, can be copied and transferred freely.
    • std::unique_ptr owns the object exclusively, copying is prohibited, only moving is allowed.
  • Safety:

    • Raw pointer can lead to errors if you forget to delete the object or use it after deletion.
    • std::unique_ptr helps avoid such errors through automatic management.

Example of using std::unique_ptr:

#include <memory>

std::unique_ptr<int> ptr = std::make_unique<int>(42);
// ptr will automatically delete the object when it goes out of scope

Thus, std::unique_ptr simplifies dynamic memory management and enhances code safety.