1. Goals
Preserve valid data through constructors and member functions.
Distinguish a copyable record from an object managing one resource.
Return a borrowed item on success, early cancellation, and failure.
2. Prerequisites
You know classes, invariants, constructors/destructors, ownership, RAII, value copying, and exceptions. This lesson combines them in a small program. Inheritance is unnecessary just because the previous lesson introduced it.
3. Explanation
A study corner has exactly one practice kit. A learner borrows it for a practice session and returns it when the session ends. The program models sessions with C++ scopes rather than waiting in real time. Minutes on the record describe the planned duration, not a timer; ending a session returns the kit immediately, even when the learner leaves early.
Maintain three rules:
A record has a nonempty borrower name and a duration from
1to120minutes.One item can have at most one active loan session.
Only a session that acquired the item is responsible for returning it.
LoanRecord owns its name in std::string and its duration in int.
Its constructor rejects invalid data with std::invalid_argument.
extendBy checks before changing anything: the extra duration must be
positive and no greater than the remaining 120 - minutes_. This avoids
adding large integers before validating them. Refusal returns false
and leaves the duration unchanged.
LoanRecord uses its default copy constructor, copy assignment, and
destructor. extended = original in a declaration creates a copy;
extending it does not change the original. You may also assign a record
to an existing record. Its value members manage their own ownership.
LoanItem represents the kit's identity and its borrowed flag. It cannot
be copied: copying a name and a busy flag would not create another real
kit. tryBorrow() returns false when busy; refusal does not disturb
the current loan. giveBack() returns the item without throwing.
LoanSession borrows a reference to LoanItem, owns a copy of
LoanRecord, and stores active_ to track whether it must return the
item. Members are declared as item_, record_, then active_. Copying
the record's string therefore completes before tryBorrow() runs.
If copying throws, no item has been acquired. After successful acquisition,
this constructor performs no further operation that can throw.
A second session can still be constructed while the item is busy, but
its active() is false. Its destructor does not return the first
session's item. The first session's destructor is responsible for
giveBack(). Copying LoanSession is deleted so two guards cannot both
believe they must release the same loan.
Usage contract: LoanItem must outlive every session borrowing it.
When using sessions, do not call giveBack() or manipulate borrowing
externally while a session holds the item. This single-threaded example
does not coordinate concurrent threads or preserve history across restarts.
runLoan returns false for a busy item or early cancellation, throws
runtime_error for a simulated failure during a session, and returns
true on completion. The local guard returns the item on success, early
return, and the path to an outer catch. Busy and cancelled both return
false because this caller only needs to know whether the run completed;
distinguishing those reasons would require a more detailed result contract.
RAII only restores the item's availability. It does not erase messages already printed or undo every action performed during a session. The destructor does not print: returning the item only changes a flag and guarantees not to throw.
4. Runnable example
Compile as C++17. The program needs no keyboard input or files and does not wait for the duration recorded on the loan.
#include <exception>
#include <iostream>
#include <stdexcept>
#include <string>
class LoanRecord {
std::string borrower_;
int minutes_;
public:
LoanRecord(const std::string& borrower, int minutes)
: borrower_(borrower), minutes_(minutes) {
if (borrower_.empty() || minutes_ < 1 || minutes_ > 120) {
throw std::invalid_argument("invalid loan record");
}
}
const std::string& borrower() const { return borrower_; }
int minutes() const { return minutes_; }
bool extendBy(int extra) {
if (extra <= 0 || extra > 120 - minutes_) {
return false;
}
minutes_ += extra;
return true;
}
};
class LoanItem {
std::string title_;
bool borrowed_ = false;
public:
explicit LoanItem(const std::string& title) : title_(title) {
if (title_.empty()) {
throw std::invalid_argument("empty item title");
}
}
LoanItem(const LoanItem&) = delete;
LoanItem& operator=(const LoanItem&) = delete;
bool tryBorrow() noexcept {
if (borrowed_) {
return false;
}
borrowed_ = true;
return true;
}
void giveBack() noexcept { borrowed_ = false; }
bool isBorrowed() const noexcept { return borrowed_; }
const std::string& title() const { return title_; }
};
class LoanSession {
LoanItem& item_;
LoanRecord record_;
bool active_;
public:
LoanSession(LoanItem& item, const LoanRecord& record)
: item_(item), record_(record), active_(item_.tryBorrow()) {}
LoanSession(const LoanSession&) = delete;
LoanSession& operator=(const LoanSession&) = delete;
~LoanSession() noexcept {
if (active_) {
item_.giveBack();
}
}
bool active() const noexcept { return active_; }
const LoanRecord& record() const { return record_; }
};
bool runLoan(LoanItem& item, const LoanRecord& record,
bool cancelEarly, bool fail) {
LoanSession session(item, record);
if (!session.active() || cancelEarly) {
return false;
}
if (fail) {
throw std::runtime_error("loan interrupted");
}
std::cout << "Using: " << item.title() << " for "
<< session.record().borrower() << " ("
<< session.record().minutes() << " min)\n";
return true;
}
int main() {
LoanRecord original("Lan", 30);
LoanRecord extended = original;
extended.extendBy(15);
LoanItem item("C++ kit");
std::cout << std::boolalpha;
std::cout << "Original minutes: " << original.minutes() << '\n';
std::cout << "Copy minutes: " << extended.minutes() << '\n';
std::cout << "Extend beyond limit: " << extended.extendBy(100) << '\n';
{
LoanSession first(item, extended);
std::cout << "First active: " << first.active() << '\n';
{
LoanSession second(item, original);
std::cout << "Second active: " << second.active() << '\n';
}
std::cout << "Still borrowed: " << item.isBorrowed() << '\n';
}
std::cout << "Borrowed after scope: " << item.isBorrowed() << '\n';
try {
runLoan(item, extended, false, true);
} catch (const std::exception& error) {
std::cout << "Error: " << error.what() << '\n';
}
std::cout << "Borrowed after error: " << item.isBorrowed() << '\n';
const bool cancelled = runLoan(item, extended, true, false);
std::cout << "Cancelled run succeeded: " << cancelled << '\n';
std::cout << "Borrowed after cancellation: " << item.isBorrowed() << '\n';
const bool completed = runLoan(item, extended, false, false);
std::cout << "Completed: " << completed << '\n';
std::cout << "Borrowed after success: " << item.isBorrowed() << '\n';
return 0;
}Output:
Original minutes: 30
Copy minutes: 45
Extend beyond limit: false
First active: true
Second active: false
Still borrowed: true
Borrowed after scope: false
Error: loan interrupted
Borrowed after error: false
Cancelled run succeeded: false
Borrowed after cancellation: false
Using: C++ kit for Lan (45 min)
Completed: true
Borrowed after success: false5. Common mistakes
Allowing direct writes to
minutes_that break the duration limits.Testing
minutes_ + extra > 120before excluding large values; the addition could overflow.Copying a guard or allowing a rejected guard to return another guard's item.
Acquiring the item before copying the record; if copying throws, the session has not finished construction, so its own destructor cannot rescue the loan.
Storing a record reference in the session while expecting an independent snapshot.
Keeping a session longer than its item or calling
giveBack()while held.Placing
giveBack()only at the end ofrunLoan, missing early returns and errors.
6. Practice
Implement the three classes before reading the example. For a
30-minute record, extending by0,-1, or91must fail and keep30; extending by90succeeds and reaches120. An empty name,0minutes, or121minutes must cause construction to throwinvalid_argument.Copy a record, then assign
LoanRecord("Minh", 60)to the copy. The original must remainLan,30minutes. Create a session from the original and extend the original by10: the session's copy stays at30.Have two sessions try to borrow the same item. The second is inactive; destroying it leaves the item busy until the first session ends. Try successful, cancelled, and throwing
runLoancalls; all must return the item.In a block with
LoanSession session(item, original), separately tryLoanSession duplicate{session};andsession = session;. Both must fail compilation. The value record can be copied; the guard's responsibility for returning an item must not be duplicated.
7. Self-check
Why does extending
extendedleaveoriginalunchanged while sessions share an item? Answer: records are copied by value and have separate members. Both sessions instead refer to the sameLoanItem; they do not copy it.Why does destroying the second session leave the item busy? Answer: its
tryBorrowreturnedfalse, soactive_isfalse. The destructor returns the item only when the session owns the loan.If
runLoanthrows, who returns the item, and when? Answer: the local session's destructor returns it while leaving the function on the way to the handler. By the timemainenterscatch, the item can be borrowed again.
Sample code
Source file
cpp98_foundation/19_stage3_practice/main.cpp
#include <exception>
#include <iostream>
#include <stdexcept>
#include <string>
class LoanRecord {
std::string borrower_;
int minutes_;
public:
LoanRecord(const std::string& borrower, int minutes)
: borrower_(borrower), minutes_(minutes) {
if (borrower_.empty() || minutes_ < 1 || minutes_ > 120) {
throw std::invalid_argument("invalid loan record");
}
}
const std::string& borrower() const { return borrower_; }
int minutes() const { return minutes_; }
bool extendBy(int extra) {
if (extra <= 0 || extra > 120 - minutes_) {
return false;
}
minutes_ += extra;
return true;
}
};
class LoanItem {
std::string title_;
bool borrowed_ = false;
public:
explicit LoanItem(const std::string& title) : title_(title) {
if (title_.empty()) {
throw std::invalid_argument("empty item title");
}
}
LoanItem(const LoanItem&) = delete;
LoanItem& operator=(const LoanItem&) = delete;
bool tryBorrow() noexcept {
if (borrowed_) {
return false;
}
borrowed_ = true;
return true;
}
void giveBack() noexcept { borrowed_ = false; }
bool isBorrowed() const noexcept { return borrowed_; }
const std::string& title() const { return title_; }
};
class LoanSession {
LoanItem& item_;
LoanRecord record_;
bool active_;
public:
LoanSession(LoanItem& item, const LoanRecord& record)
: item_(item), record_(record), active_(item_.tryBorrow()) {}
LoanSession(const LoanSession&) = delete;
LoanSession& operator=(const LoanSession&) = delete;
~LoanSession() noexcept {
if (active_) {
item_.giveBack();
}
}
bool active() const noexcept { return active_; }
const LoanRecord& record() const { return record_; }
};
bool runLoan(LoanItem& item, const LoanRecord& record,
bool cancelEarly, bool fail) {
LoanSession session(item, record);
if (!session.active() || cancelEarly) {
return false;
}
if (fail) {
throw std::runtime_error("loan interrupted");
}
std::cout << "Using: " << item.title() << " for "
<< session.record().borrower() << " ("
<< session.record().minutes() << " min)\n";
return true;
}
int main() {
LoanRecord original("Lan", 30);
LoanRecord extended = original;
extended.extendBy(15);
LoanItem item("C++ kit");
std::cout << std::boolalpha;
std::cout << "Original minutes: " << original.minutes() << '\n';
std::cout << "Copy minutes: " << extended.minutes() << '\n';
std::cout << "Extend beyond limit: " << extended.extendBy(100) << '\n';
{
LoanSession first(item, extended);
std::cout << "First active: " << first.active() << '\n';
{
LoanSession second(item, original);
std::cout << "Second active: " << second.active() << '\n';
}
std::cout << "Still borrowed: " << item.isBorrowed() << '\n';
}
std::cout << "Borrowed after scope: " << item.isBorrowed() << '\n';
try {
runLoan(item, extended, false, true);
} catch (const std::exception& error) {
std::cout << "Error: " << error.what() << '\n';
}
std::cout << "Borrowed after error: " << item.isBorrowed() << '\n';
const bool cancelled = runLoan(item, extended, true, false);
std::cout << "Cancelled run succeeded: " << cancelled << '\n';
std::cout << "Borrowed after cancellation: " << item.isBorrowed() << '\n';
const bool completed = runLoan(item, extended, false, false);
std::cout << "Completed: " << completed << '\n';
std::cout << "Borrowed after success: " << item.isBorrowed() << '\n';
return 0;
}