Chapter 5 – Object lifetime

Memory allocation

Memory allocation is the process of reserving computer memory for the execution of programs and processes.

Static memory

Static memory refers to memory allocated by the compiler in advance, based on the variable declarations in the code.

This is where variables that are defined outside of functions are located (globals, static).

Local memory

Local memory refers to memory allocated on the stack by the application when a function is called, and is destroyed and freed up when the function exits.

Dynamic memory

Dynamic memory refers to memory allocated on demand during runtime (on the heap), and is under the control of the programmer. It exists as long as you need it and is destroyed explicitly when you free it up.

Operator new/delete

Assuming we have the following class:

We can allocate memory on the heap (and destroy it) as such:

Smart pointers

A smart pointer is a wrapper that uses the RAII concept (perform operation on constructor and on destructor – usually resource allocation).

And we can create an object as such:


Unique pointer is the default go-to when switching from old C++ to C++11 and above.

The problem with the line from above is that we can encounter problems, if we send a pointer that is already owned by another smart pointer.

If we send the pointer to two instances, both of them will believe that they have ownership on it, and they deallocate the memory when going out of scope. When the second instance goes out of scope, double delete error occurs.

The solution here is to use make_unique function, which further calls the new operator inside.


shared_ptr is similar to unique_ptr, but the object does not have ownership on the resource, but it is shared among instances. When the last one goes out of scope, the memory is deallocated.

When returning a shared_ptr from inside of a class, based on the current instance, we should use shared_from_this to assure that the shared_ptr is created correctly.

Below you can see a good and a bad example of creating a shared pointer from the this object.

You may also like...