1. Goals
Identify who must release a resource and who only borrows it.
Use a destructor to release resources on normal and early returns.
Recognize leaks, double deletion, and mismatched allocation in older code.
2. Prerequisites
You know classes, constructors, destructors, references, and lifetimes. This lesson models a study room with one reservation; it does not open files, connect to a network, or allocate memory manually. Compile as C++17.
3. Explanation
A resource is not necessarily memory: a reservation, an open file, or a held lock may need to be released. The owner is responsible for releasing it; a borrower may use it within an agreed lifetime but does not release it. A plain pointer or reference alone does not describe that responsibility.
RAII attaches this responsibility to an object: acquire the resource during
construction and release it in the destructor. For an automatic local object,
leaving its block through return still calls the destructor. Cleanup no
longer has to be repeated in every branch. This follows the
resource handle guidance in the C++ Core Guidelines.
The error-handling lesson covers exceptions. RAII does not promise cleanup
when a process is forcibly terminated.
StudyRoom models room availability. RoomReservation borrows the room
through StudyRoom&, but owns the obligation to release an acquired
reservation. If the room is busy, owns_ is false; that object must not
release somebody else's reservation. The room must outlive every reservation
that refers to it. In main, it survives both function calls, while each
reservation lives only inside the function.
tryReserve and release are the low-level operations of this model. Code
using a reservation does not call release itself, or modify or assign the
room while a reservation is active. The example is single-threaded; it is
not a lock protecting data shared between threads.
The two declarations with = delete prohibit copying and assignment.
Do not confuse this syntax with the memory deallocation expression delete.
If two copies both believed they owned one reservation, one could release
the room while the other was still using it.
Copying and assignment are also prohibited for the room: it has its own
identity, and its state must not be overwritten by another room.
StudyRoom() = default requests the usual no-argument constructor;
occupied_ starts as false.
You have already used a ready-made owning type: std::string stores text
and manages its own memory. A std::string member is destroyed automatically
with its containing object; you do not call delete on it. A reference to
the string borrows its data and does not extend its owner's lifetime in
this use.
When reading older code, recognize the pairs: new int(7) creates one int
and requires delete p exactly once; new int[3]{} creates an array and
requires delete[] p. Do not mix these pairs or delete the address of a
local variable or an interior pointer instead of the pointer returned by
new or new[]. Losing the last pointer to allocated memory without
releasing it causes a leak. Deleting the same
allocation twice or accessing it after deletion causes undefined behavior.
Setting one pointer to nullptr does not repair other dangling aliases.
These are clues for reading and repairing older code; this lesson's practice
uses an owning object instead of asking you to manage new and delete.
After completing Foundation, revisit and extend resource management in Destructors and RAII on the C++11 track.
4. Runnable example
Save as main.cpp, compile as C++17, and run; no input is needed.
#include <iostream>
class StudyRoom {
public:
StudyRoom() = default;
StudyRoom(const StudyRoom&) = delete;
StudyRoom& operator=(const StudyRoom&) = delete;
bool tryReserve() {
if (occupied_) {
return false;
}
occupied_ = true;
return true;
}
void release() {
occupied_ = false;
}
bool occupied() const {
return occupied_;
}
private:
bool occupied_ = false;
};
class RoomReservation {
public:
explicit RoomReservation(StudyRoom& room)
: room_(room), owns_(room.tryReserve()) {}
~RoomReservation() {
if (owns_) {
room_.release();
}
}
RoomReservation(const RoomReservation&) = delete;
RoomReservation& operator=(const RoomReservation&) = delete;
bool ownsReservation() const {
return owns_;
}
private:
StudyRoom& room_;
bool owns_;
};
bool runSession(StudyRoom& room, bool cancelEarly) {
RoomReservation reservation(room);
std::cout << "Acquired: " << reservation.ownsReservation() << '\n';
if (!reservation.ownsReservation()) {
std::cout << "Room busy\n";
return false;
}
std::cout << "During session: " << room.occupied() << '\n';
if (cancelEarly) {
std::cout << "Cancelled\n";
return false;
}
std::cout << "Completed\n";
return true;
}
int main() {
std::cout << std::boolalpha;
StudyRoom room;
runSession(room, false);
std::cout << "After normal return: " << room.occupied() << '\n';
runSession(room, true);
std::cout << "After early return: " << room.occupied() << '\n';
return 0;
}Output:
Acquired: true
During session: true
Completed
After normal return: false
Acquired: true
During session: true
Cancelled
After early return: false5. Common mistakes
Calling
releaseonly at the end of a function; early returns skip it.Omitting the
owns_check; a failed reservation then releases another owner's room.Using a reservation after the room dies; its reference does not keep the room alive.
Copying an object responsible for cleanup without defining what that copy means.
Deleting a borrowed address or pairing
new[]withdelete.
6. Practice
Add another cancellation branch after the
During sessionline. The room must be free after the function returns through either branch.Create
RoomReservation first(room);inside a block. Whilefirstlives, createsecondin a nested block:second.ownsReservation()must befalse. After the inner block ends, the room is still occupied; only leaving the outer block frees it.With
firstfrom the previous exercise, separately tryRoomReservation copy(first);: compilation must fail because copying is deleted. Remove this line before running; do not remove= deletemerely to silence the error.Read a function with
new int[3]{}and tworeturnbranches. Identify who must release the array, the matching deallocation expression, and the branch likely to miss cleanup. Do not execute incorrect deletion to try to predict its result.
7. Self-check
Does
RoomReservationown theStudyRoomobject? Answer: no, it borrows the room through a reference. After successfully reserving, it owns the obligation to release that reservation.mainstill holds the room, which must live longer.Why does cancellation through
return falsestill free the room? Answer: the fully constructed reservation is an automatic local object. Before the function returns, its destructor releases the reservation ifowns_istrue.Does copying a pointer create an independent owner? Answer: no. Both pointers hold the same address; if both deallocate it, the second deletion is invalid. Define ownership clearly, usually through an owning type or by prohibiting copying.
Sample code
Source file
cpp98_foundation/15_ownership_raii/main.cpp
#include <iostream>
class StudyRoom {
public:
StudyRoom() = default;
StudyRoom(const StudyRoom&) = delete;
StudyRoom& operator=(const StudyRoom&) = delete;
bool tryReserve() {
if (occupied_) {
return false;
}
occupied_ = true;
return true;
}
void release() {
occupied_ = false;
}
bool occupied() const {
return occupied_;
}
private:
bool occupied_ = false;
};
class RoomReservation {
public:
explicit RoomReservation(StudyRoom& room)
: room_(room), owns_(room.tryReserve()) {}
~RoomReservation() {
if (owns_) {
room_.release();
}
}
RoomReservation(const RoomReservation&) = delete;
RoomReservation& operator=(const RoomReservation&) = delete;
bool ownsReservation() const {
return owns_;
}
private:
StudyRoom& room_;
bool owns_;
};
bool runSession(StudyRoom& room, bool cancelEarly) {
RoomReservation reservation(room);
std::cout << "Acquired: " << reservation.ownsReservation() << '\n';
if (!reservation.ownsReservation()) {
std::cout << "Room busy\n";
return false;
}
std::cout << "During session: " << room.occupied() << '\n';
if (cancelEarly) {
std::cout << "Cancelled\n";
return false;
}
std::cout << "Completed\n";
return true;
}
int main() {
std::cout << std::boolalpha;
StudyRoom room;
runSession(room, false);
std::cout << "After normal return: " << room.occupied() << '\n';
runSession(room, true);
std::cout << "After early return: " << room.occupied() << '\n';
return 0;
}