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 pointer std::auto_ptr, which exclusively takes care of the lifetime of a resource. But std::auto_ptr has a conceptional issue. If you implicitly or explicitly copy an std::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. So std::auto_ptr is deprecated in C++11 and you should use instead std::unique_ptr. You can neither implicitly or explicitly copy an std::unique_ptr. You can only move it.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy