Search⌘ K

Return const Pointers

Explore the principles of returning const pointers in C++, focusing on safe memory management and the implications of const placement. Understand when to return pointers, avoid dangling pointers, and the difference between const pointer styles to write clearer, safer code.

We'll cover the following...

Pointers are similar to references in the sense that the pointed object must be alive at least as long as the caller wants to use it. We can return the address of a member variable if we know that the owning object will not get destroyed considering the caller wants to dereference the pointer. It is important to emphasize that we should never return a pointer to a local variable.

However, that is not self-evident. Let’s step back a little bit.

When to return a pointer?

We return a memory address where the address can be anything. Technically, it can be a random place, a null ...