Smooth intro to Smart Pointers

Smooth intro to Smart Pointers

under the name of RAIL

·

2 min read

have you ever wondered what's going on inside the man who created the pointer? though it is a vivid topic and needs more to talk about briefly what you see in everyday life is what so-called row pointers. row pointers are mysterious and hard to fall in love with as there are many pitfalls.

  1. you don't know when exactly to use delete or delete[]

  2. you don't know if it points to a single object or an array.

  3. no way to tell the pointer is dangles. dangling pointers arise when the object points to are destroyed while the pointers still pointing to them.

but fortunately, they invited four abstracted pointers from the row pointer.

  1. std::auto_ptr

  2. std::unique_ptr

  3. std::shared_ptr

  4. std::weak_ptr

the std::auto_ptr is exactly like the std::unique_ptr so they removed it from the list.

Unique_ptr

the uniqueness of the pointer comes from the ownership of resources. it means when you move the pointer the first one is set to null while the ownership is transferred to the copied version. In addition, you can't copy the pointer because you will end up with two unique pointers pointing to the same address.

Advanced pointers

  • they are fast, small and move only smart pointers for managing the resources with exclusive ownership.

  • by default, resource destruction takes place vis delete, but custom deletes can be specified. Stateful deleters and function pointers as deleters increase the size of std::unique_ptr objects.

  • Converting a std::unique_ptr to std::shared_ptr is pretty easy.