Memory Ownership

Learn about memory ownership in programming, including handling resources implicitly and using containers.

Resource ownership in programming

Ownership of resources is a fundamental aspect to consider when programming. An owner of a resource is responsible for freeing the resource when it is no longer needed. A resource is typically a block of memory but could also be a database connection, a file handle, and so on. Ownership is important, regardless of which programming language you are using. However, it is more apparent in C and C++ since dynamic memory is not garbage-collected by default. Whenever we allocate dynamic memory in C++, we have to think about the ownership of that memory. Fortunately, there is now very good support in the language for expressing various types of ownership by using smart pointers.

The smart pointers from the standard library help us specify the ownership of dynamic variables. Other types of variables already have defined ownership. For example, local variables are owned by the current scope. When the scope ends, the objects created inside the scope will be automatically destroyed.

Get hands-on with 1400+ tech skills courses.