Unique Pointer (unique_ptr)
Introduced in C++11, included in the <memory> library as expected. Learned in CS247 - Software Engineering Principles.
Use cases for
unique_ptr
unique_ptrare good for representing ownership (owns-a), since when one object dies, itsunique_ptrfields will run and clean up the associated object.
You can access the underlying raw pointer of a smart pointer via .get().
Do not create
unique_ptrwith a pointer.
Preferred alternative:
std::make_unique<T>(...)This constructs a
Tobject in the heap with arguments (…), and returns aunique_ptr<T>pointing at this object.