Recall & Review
beginner
What is a reference lifetime in C++?
The reference lifetime is the period during which a reference variable refers to a valid object. It must not outlive the object it references to avoid undefined behavior.
Click to reveal answer
beginner
Why is it dangerous for a reference to outlive the object it refers to?
If a reference outlives its object, it becomes a dangling reference. Accessing it leads to undefined behavior, such as crashes or corrupted data.
Click to reveal answer
intermediate
How does returning a reference to a local variable affect reference lifetime?
Returning a reference to a local variable is unsafe because the local variable is destroyed when the function ends, leaving the reference dangling.
Click to reveal answer
intermediate
What is a common safe practice to extend the lifetime of a temporary object when using references?
Binding a const reference to a temporary object extends the temporary's lifetime to match the reference's lifetime, making it safe to use.Click to reveal answer
advanced
Explain the difference between lvalue and rvalue references in terms of lifetime.
Lvalue references refer to objects with a stable address and longer lifetime. Rvalue references usually bind to temporary objects with short lifetimes, so care is needed to avoid dangling references.
Click to reveal answer
What happens if a reference in C++ outlives the object it refers to?
✗ Incorrect
A reference that outlives its object points to invalid memory, causing undefined behavior.
Which of the following safely extends the lifetime of a temporary object?
✗ Incorrect
Binding a temporary to a const reference extends its lifetime to match the reference.
Why is returning a reference to a local variable unsafe?
✗ Incorrect
Local variables are destroyed when the function returns, so references to them become invalid.
Which type of reference usually binds to temporary objects?
✗ Incorrect
Rvalue references are designed to bind to temporary (rvalue) objects.
What is a dangling reference?
✗ Incorrect
A dangling reference points to memory that has been freed or is no longer valid.
Describe what happens to a reference's validity when the object it refers to is destroyed.
Think about what happens if you keep a pointer to a deleted object.
You got /3 concepts.
Explain how binding a const reference to a temporary object affects the temporary's lifetime.
Consider how const references can keep temporary objects alive longer.
You got /3 concepts.