(C++) std::unique\_ptr
January 26, 2018 · View on GitHub
(C++)
std::unique_ptr
std::unique_ptr is an C++11 STL uncopyable smart pointer.
std::unique_ptr is similar to boost::scoped_ptr.
std::unique_ptr guarantees that its value is complete when destroyed [1].
Example
Advice
- Use std::unique_ptr to refer to objects of polymorphic type [2]
- Prefer std::unique_ptr over std::shared_ptr [3]
Comparison of std::unique_ptr and boost::scoped_ptr
- boost::scoped_ptr can be used from every C++ standard, std::unique_ptr from C++11
- std::unique_ptr is part of the official C++11 standard
- std::unique_ptr has a 'release' member function
References
- Working Draft, Standard for Programming Language C++. N3337. 2012-01-16. Paragraph 20.7.1.2.2: 'unique_ptr destructor [unique.ptr.single.dtor]', page 518: '1 Requires: The expression get_deleter()(get()) shall be well formed, shall have well-defined behavior, and shall not throw exceptions. [Note: The use of default_delete requires T to be a complete type. —end note]'
- Bjarne Stroustrup. A tour of C++. 2014. ISBN: 978-0-321-958310. Chapter 11.7.5, page 131: 'Use unique_ptr to refer to objects of polymorphic type'
- Bjarne Stroustrup. A tour of C++. 2014. ISBN: 978-0-321-958310. Chapter 11.7.8, page 131: 'Prefer unique_ptr over shared_ptr'