Object lifetime and resource ownership
Use lifetime to make cleanup predictable in C++.
What you’ll learn
- Distinguish ownership from access
- Explain scope-based cleanup
- Prefer standard owning types
Resources need an owner
A resource is something that must eventually be released: dynamically allocated memory, a file handle, a lock, or another limited facility. Ownership answers who is responsible for that release. Merely storing an address does not explain ownership, and several raw pointers to one object can make the responsibility ambiguous. Start a design by identifying the owner, the allowed lifetime, and the operations that temporarily borrow access. Clear ownership simplifies both the normal path and the error path.
Connect cleanup to lifetime
Resource Acquisition Is Initialization is a C++ design technique that connects resource ownership to an object's lifetime. Construction acquires or accepts responsibility for a resource, and destruction releases it. An automatic object is destroyed when its scope ends, including normal stack unwinding during an exception. This does not mean every termination mechanism runs every destructor; abrupt process termination is a different situation. The value is that ordinary control flow does not require duplicated cleanup statements after each possible return.
Choose standard owners first
A std::string owns its character storage and a std::vector owns its element storage. A file-stream object manages a file resource, while a lock guard manages a lock within a scope. These types let your program express ownership without writing a custom destructor for every class. When a class can be composed entirely from appropriate owning members, the compiler-generated special member functions are often sufficient. This is the motivation behind preferring the rule of zero for straightforward resource-owning classes.
#include <fstream>
#include <string>
int main() {
std::ifstream input("notes.txt");
if (!input) return 1;
std::string line;
std::getline(input, line);
} // input closes its file as its lifetime endsDistinguish borrowing and sharing
A reference or non-owning pointer can provide access without transferring ownership, but the referenced object must outlive that access. A unique_ptr expresses exclusive ownership of a dynamically allocated object. A shared_ptr represents shared ownership through a control block, which introduces its own costs and the possibility of ownership cycles. Do not choose shared ownership merely to avoid deciding who owns an object. Often the clearer design is one owner and several bounded borrowers.
Review all exit paths
Consider a function that opens a file, reads input, and returns early when validation fails. If the file is owned by a scoped standard object, leaving the scope performs cleanup. With manual ownership, every early return and exception can become a leak risk. Test both success and failure paths, and inspect whether borrowed references escape their owner's lifetime. Tools such as sanitizers can help discover invalid accesses, but they support an ownership design rather than replace it.
Try it yourself
Explain why a local standard file-stream object is preferable to manually closing a raw file resource at the bottom of a function.
Show a possible solution
The owning object releases the resource when its lifetime ends, so early returns and ordinary exception unwinding do not need duplicated close calls. Manual cleanup at only the final line misses other exit paths.
Check your understanding
Try 14 questions across modern c++ foundations. Read each explanation and revisit anything that needs another pass.
Practise this subjectGo 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.