Unique Pointers
The first type of smart pointer in this section is the unique pointer. It limits the access to its resource, thereby, maintaining its privacy.
We'll cover the following
std::unique_ptr exclusively takes care of its resource. It automatically releases the resource if it goes out of scope. If there is no copy semantic required, it can be used in containers and algorithms of the Standard Template Library. std::unique_ptr
is as cheap and fast as a raw pointer, if you use no special deleter.
⚠️ Don’t use std::auto_ptr
Classical C++03 has a smart pointerstd::auto_ptr
, which exclusively takes care of the lifetime of a resource. Butstd::auto_ptr
has a conceptional issue. If you implicitly or explicitly copy anstd::auto_ptr
, the resource is moved. So instead of the copy semantic, you have a hidden move semantic, and therefore you often have undefined behavior. Sostd::auto_ptr
is deprecated in C++11 and you should use insteadstd::unique_ptr
. You can neither implicitly or explicitly copy anstd::unique_ptr
. You can only move it.
Create a free account to view this lesson.
Continue your learning journey with a 14-day free trial.
By signing up, you agree to Educative's Terms of Service and Privacy Policy