how to use c++ 11 smart pointersThe basic intent to use smart pointers in c++ is to avoid memory leaks. The c++ 11 provides three standard smart pointers unique_ptr, shared_ptr and weak_ptr.  Use of these pointers minimize the chances of memory leaks. These pointers delete the memory of heap allocated objects when they go out of scope. The improper use of smart pointer can cause memory leaks in c++ program. Here will will discuss most of the things about unique_ptr, shared_ptr and weak_ptr.

How to use c++ 11 smart pointers?

C++ provides two operators “new” and “delete”. new is used to allocate memory at heap and delete is used to delete memory allocated at heap. It is necessary to delete an object created by new. who and when will it be deleted?


  • unique_ptr has unique ownership. it does not share its pointer. An object is owned by only and only one unique_ptr. so the below code will not compile.

  • unique_ptr can not be copied but it can transfer the ownership by std:move. For example in the above code the man_from_us is unique_ptr and owns Man. By the property at any point of time man_from_us can own only object. It cannot passed by value to a function, or used in any STL algorithm that requires copies to be made. A unique_ptr can only be moved.

  • Only non const unique_ptr can transfer the ownership of the managed object to another unique_ptr. so below code will give compile time error because man_from_us is a const object.

Note: The reset, release, swap, and move assignment functions are non const member functions and therefore cannot be used with a const instance of the std::unique_ptr class.




Read Next Article : for shared_ptr and weak_ptr