Object Lifetime and Scope
Before choosing a smart pointer, you must know when a C++ object begins to exist and when it is destroyed.
Learning goal
After this lesson, you should be able to explain:
- the difference between an object's lifetime and a name's scope;
- when local objects are constructed and destroyed;
- why leaving a block performs automatic cleanup;
- why a pointer does not keep the object it points to alive.
Start with a simple example
Output:
desk_lamp is created when execution reaches its declaration. It is destroyed
automatically when main ends. No manual cleanup is required.
Scope and lifetime are different
Scope describes where a name can be used in the source code.
Lifetime describes the period during execution when an object exists and may be safely used.
For these local variables, scope and lifetime end at the same closing brace. That is common, but the terms do not mean the same thing. Later lessons will show pointers whose names remain in scope after the objects they point to have already been destroyed.
Nested scopes
A pair of braces creates a block. An object declared inside a block is cleaned up when execution leaves that block, including when the function returns early or throws an exception.
Objects in the same scope are destroyed in the reverse order of their completed construction. This matters when one object depends on another.
Predict the behavior
Before opening the answer, write down the exact output:
Show the expected output
`third` is destroyed before `second` because they were constructed in the opposite order. `first` lives until the end of `main`.Compile the experiment
Save the program as lifetime.cpp, then compile and run it:
Try moving third outside the inner braces. Predict its new destruction point
before compiling again.
Ownership begins with cleanup responsibility
The owner of a resource is responsible for releasing it. A local value normally owns its own resources and cleans them up in its destructor:
This is the foundation of RAII and smart pointers. Smart pointers are useful later when an object must be owned indirectly, but a normal value is the simplest choice when it works.
A pointer does not extend lifetime
The variable observer is still in scope, but the value object no longer
exists. A pointer only stores an address; it does not automatically own the
object or keep it alive.
Small coding exercise
Create a Book class that:
- Stores a title.
- Prints
Open: TITLEin its constructor. - Prints
Close: TITLEin its destructor. - Creates one
Bookinmainand two more inside a nested block.
Before running it, predict the destruction order. Then add an early return
inside the nested block and confirm that all constructed books are still
destroyed.
Quiz
1. What does object lifetime describe?
2. When is a normal local object destroyed?
3. In what order are local objects in one scope destroyed?
4. Does a raw pointer keep a local object alive?
5. What is the simplest ownership choice for a local object?
Code-review challenge
What is wrong with this function?
Show the review
`name` is destroyed when `make_name` returns. The returned pointer therefore points to an object that no longer exists. Dereferencing it causes undefined behavior. Return the string by value: The caller receives its own valid `std::string`. No pointer or smart pointer is needed.Lesson summary
- Scope controls where a name can be used.
- Lifetime controls when an object exists.
- Local objects are destroyed automatically when execution leaves their block.
- Local objects in one scope are destroyed in reverse construction order.
- A pointer does not keep another object alive.
- Prefer normal values when they express the required ownership.
Next: raw pointers and references as non-owning observers.