Chapters & contents Lesson 20 of 20
3 min read
Modern C++ foundationsExpanded reading

Values, references, and ownership that can be explained

Use standard containers and scoped resource owners to make lifetimes visible.

What you’ll learn

  • Distinguish a copied value from an alias
  • Trace destruction at the end of a scope
  • Recognize a dangling reference and choose a safer return value

Ask who keeps the object alive

A C++ object has a lifetime, and another variable can refer to it without extending that lifetime in general. Begin with ordinary values: a std::vector owns storage for its elements and releases that storage through its normal resource management. A reference to a vector provides another way to access the same object; it does not become a second independent vector. Explaining these relationships is more useful than treating every parameter as a mysterious address or assuming all objects need explicit dynamic allocation.

Trace a copy and an alias

Create vector original with values 3 and 6. Define copy by copying original, and define alias as a reference to original. Appending 9 through alias changes original to [3, 6, 9], while copy remains [3, 6]. This example is about vectors of integers; copying a container of owning or non-owning handles requires reasoning about the handle types too. Read the element type as well as the container type before concluding what a copy duplicates.

cpp · Worked example
#include <iostream>
#include <vector>

int main() {
    std::vector<int> original{3, 6};
    auto copy = original;
    auto& alias = original;
    alias.push_back(9);
    std::cout << original.size() << " " << copy.size() << "\n";  // 3 2
}

Tie resources to scope

Resource Acquisition Is Initialization, commonly called RAII, associates a resource with an object that manages its lifetime. A scoped file stream can close its file, and a scoped lock owner can release its lock when the owner is destroyed. This applies during normal scope exit and relevant stack unwinding paths. It reduces the number of manual cleanup branches a programmer must maintain. It does not mean that failures, process termination, or every operating-system resource concern disappear; the owner’s documented contract still matters.

Reject a reference to a departed object

A function that creates a local vector and returns a reference to it leaves the caller referring to an object whose lifetime has ended. The source may compile with a warning, but compilation does not make the reference valid. Returning the vector by value expresses transfer of a result safely and allows language and library mechanisms to handle construction or movement as applicable. Do not return a pointer to the local object as a cosmetic repair; the same lifetime problem remains.

Make ownership explicit only where needed

Prefer ordinary values and standard containers when they express the model. When dynamic ownership is required, use an appropriate owner such as std::unique_ptr for exclusive ownership instead of an unexplained owning raw pointer. A non-owning pointer or reference can still be useful, but the API must make the owner and validity period understandable. Test a small object graph and draw which object owns which resource. Clear ownership reduces both leaks and use-after-lifetime errors without requiring every relationship to become shared ownership.

Try it yourself

A function creates a local std::vector<int> and returns const std::vector<int>& to it. Why is the result unsafe, and what return type would you choose for a newly computed sequence?

Show a possible solution

The local vector is destroyed when the function exits, so the returned reference dangles. Return std::vector<int> by value for a newly computed sequence. A const qualifier prevents modification through a reference but does not extend this local object’s lifetime.

Check your understanding

Try 14 questions across modern c++ foundations. Read each explanation and revisit anything that needs another pass.

Practise this subject

Go to the source

Use these primary references to check details and explore the topic further.

Saved in this browser. Signed-in progress syncs to your account.