From the course: Object-Oriented Programming with C++

Unlock this course with a free trial

Join today to access over 24,400 courses taught by industry experts.

Smart use of smart pointers

Smart use of smart pointers - C++ Tutorial

From the course: Object-Oriented Programming with C++

Smart use of smart pointers

- [Instructor] Managing dynamic memory and C++ can be challenging and error prone. Even experienced developers sometimes forget to delete objects or accidentally delete them multiple times. Smart pointers solve these problems by automating memory management. They rep raw pointers in a class that handles the location automatically when the smart pointer goes out of scope. This follows, the resource acquisition is initialization principle, where resource management is tied to object lifetime. C++ provides three types of smart pointers, each serving different ownership scenarios. The most commonly used is the unique_ptr, which expresses exclusive ownership. When you create a unique_ptr, it becomes the sole owner of the object it points to. So here's how it looks. The main idea behind unique ownership is that it cannot be shared. Only one pointer can own the resource at a time. That said, unique ownership can be transferred using std::move. The move operation makes it explicit that we're…

Contents