0
0
C++programming~5 mins

Reference lifetime in C++ - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
ANothing, the reference remains valid.
BThe reference automatically updates to a new object.
CThe program throws a compile-time error.
DIt becomes a dangling reference causing undefined behavior.
Which of the following safely extends the lifetime of a temporary object?
ABinding it to a const reference.
BReturning a reference to a local variable.
CUsing a non-const reference to a temporary.
DAssigning it to a pointer.
Why is returning a reference to a local variable unsafe?
ABecause local variables have static lifetime.
BBecause references cannot be returned from functions.
CBecause the local variable is destroyed after the function ends.
DBecause references copy the object.
Which type of reference usually binds to temporary objects?
ARvalue references.
BLvalue references.
CConst lvalue references.
DPointer references.
What is a dangling reference?
AA reference that is null.
BA reference that points to an object that no longer exists.
CA reference that points to a valid object.
DA reference that points to a global variable.
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.