topskill.dev
CoursesTracks
All courses/C++ ProgrammingKeep Borrowed Access Within Its Lifetime
References and Pointers
7 / 8
← C++ Programming
○Welcome to C++○Change a Message○Write Two Lines○Read a Program○Comments and Spacing○Name a Value○Update a Value○Build an Announcement Card✦Module Quiz
○Choose a Type○Characters and Booleans○Keep a Constant○Arithmetic and Precedence○Division and Remainders○Convert a Number○Format a Price○Calculate a Receipt✦Module Quiz
○Compare Values○Combine Conditions○Choose with if○Choose an Alternative○Choose Between Ranges○Select with switch○Pick a Short Result○Price a Ticket✦Module Quiz
○What Is a Loop?○Repeat with While○Count with For○Build a Running Total○Run at Least Once○Stop or Skip○Rows and Columns○Plan Seating for a Workshop✦Module Quiz
○Return a Result○Pass Arguments○Perform an Action○Keep Names Local○Declare Before Use○Supply a Default Argument○Overload a Function○Build Price Helpers✦Module Quiz
○Store and Join Text○Read Characters Safely○Find and Slice Text○Change a String○Read Values from Text○Write a Text Report✦Module Quiz
○Keep a Fixed Set of Counts○Add Values to a Vector○Visit Every Value○Revise a List Safely○Read Rows and Columns○Recognize a Raw Array○Summarize Shelf Stock✦Module Quiz
○Give a Value Another Name○Read Without Copying a Collection○Let a Function Update the Caller○Point to an Existing Value○Handle a Missing Target○Separate a Fixed Target from Read-Only Access●Keep Borrowed Access Within Its Lifetime✦Module Quiz
○Keep Related Fields in a Struct○Read and Update Records in Functions○Give States Meaningful Names○Keep a Collection of Records○Report Stock by Record and State✦Module Quiz
○Introduce a Class○Initialize with a Constructor○Protect an Invariant○Read a Const Object○Compose Small Objects○Share a Class Constant○Copy an Object○Grant a Friend Access○Build a Basket✦Module Quiz
○Follow a Scope○Observe a Destructor○Allocate and Release○Own with unique_ptr○Transfer Ownership○Prefer the Rule of Zero✦Module Quiz
○Understand Iterators○Sort a Range○Find and Count○Write a Lambda○Capture a Value○Accumulate a Total○Look Up with map○Keep Unique Values○Use a Stack and a Queue○Work at Both Ends○Insert in a List○Organize a Packing List✦Module Quiz
○Organize with Namespaces○Name a Type○Compute with constexpr○Check an Assumption○Write a Function Template○Write a Class Template○Overload an Operator○Pass a Function○Follow Recursion✦Module Quiz
○Extend a Class○Override a Virtual Function○Use an Abstract Base○Avoid Object Slicing○Destroy Through a Base○Check a Derived Type○Choose Composition✦Module Quiz
○Read Binary Flags○Combine Bit Masks○Respect Numeric Limits○Return a Status○Repeat a Random Sequence○Use Math Functions○Diagnose a Wrong Result✦Module Quiz
○Create the Catalog○Find a Book○Lend and Return○Summarize the Shelves○Print the Library Report○Where to Go Next✦Module Quiz
References and Pointers

Keep Borrowed Access Within Its Lifetime

A pointer or reference does not keep an ordinary local object alive. It gives access to an object that must already exist. Think of this as borrowed access: the borrowing code is responsible for staying within the object's lifetime.

A local variable normally lives until execution leaves its enclosing block. A function's local variable therefore cannot safely be returned by pointer or reference for later use. Returning its value is different: the result is a separate value that the caller can keep.

cpp
#include <iostream>
int startingCount() {
    int count = 6;
    return count;
}
int main() {
    int saved = startingCount();
    const int* view = &saved;
    std::cout << *view << '\n';
}

This safe example prints 6. saved is alive when view is used. The local count inside the function has already gone away, but no pointer to it escaped. The function returned a value, not borrowed access.

When a collection changes

A vector may move its elements to new storage as it grows. If that happens, pointers and references to the previous element locations are invalid, even though the vector variable itself is still alive. Removing an element also ends that element's lifetime. Do not keep and use an old pointer to a removed element.

A simple safe pattern is to finish structural changes first and then obtain any pointer or reference you need. For an element you will revisit, keeping an index can be useful, but validate it against the current size before accessing the vector again. An index is not a permanent identity if earlier elements are removed or reordered.

cpp
#include <vector>
#include <iostream>
int main() {
    std::vector<int> counts{3};
    counts.push_back(8);
    const int& first = counts[0];
    std::cout << first << '\n';
}

Here the reference is acquired after growth, and no later structural change occurs before the read. The printed value is 3.

A null check is not a lifetime check

A dangling pointer refers to an object whose lifetime has ended. It does not automatically turn into nullptr. Comparing such a saved pointer with null is not a way to establish that the former target is still alive. Arrange your code so it never uses that pointer after the target ends instead.

When you read a pointer or reference in a program, trace it back to the object it identifies. Then check whether execution can leave that object's block, or change its collection's storage, before the access happens. A null check cannot answer those questions. Keep borrowed access short: use it while the target is known to be alive, and return a value when the caller needs to keep a local calculation's result. Later ownership lessons will cover objects that need a different lifetime.

The diagram shows the other lifetime boundary: leaving a block rather than changing a collection. Follow the target's lifetime, not just the pointer variable's scope.

The pointer outlives the object in the inner block. Its old address must not be used to read or write that object after the closing brace.