Sub topic 1
Resources, lifetimes, and ownership
Resources and lifetimes
A resource is something a program acquires and must later release, such as memory or an open file. An object is a piece of data with a type, such as a std::string.
An object’s lifetime is the time from its creation to its destruction. Ownership means responsibility for managing and releasing a resource. For example, a string manages the storage for its characters and cleans up when the string is destroyed.
Copying versus transferring
Copying a string creates a separate string with the same value. Changing one string does not change the other.
Transferring a resource instead gives another object responsibility for it. This can avoid duplicating data. The old owner’s state after a transfer depends on its type. Later chapters show how C++ performs transfers.
Lvalues and rvalues
An expression is a piece of code that produces a value or identifies an object. Expressions have categories that affect how they can be used.
- An lvalue usually identifies an existing object. A variable name such as
numberis an lvalue. - An rvalue can be a temporary value, such as
42, or an object whose resources may be transferred.
These categories describe expressions, not types.
Rvalue references
A reference is another way to refer to an object. An rvalue reference, written with &&, can bind to an rvalue. Binding means connecting the reference to an object.
Run this example:
#include <iostream>
#include <string>
void inspect(int& value) {
std::cout << "lvalue " << value << '\n';
}
void inspect(int&& value) {
std::cout << "rvalue " << value << '\n';
}
int main() {
std::string original = "cat";
std::string copy = original;
copy[0] = 'b';
std::cout << original << " " << copy << '\n';
int number = 7;
int&& ref = 42;
inspect(number);
inspect(42);
inspect(ref);
}The first line printed is cat bat: the strings are separate objects. The two inspect functions accept different kinds of references. C++ selects the matching function for each call.
Although ref is an rvalue reference, the expression ref is an lvalue because it has a name. The temporary integer bound to ref stays alive for the lifetime of ref.
Exercise
Which version of inspect handles inspect(ref), and why?
Show answer
The int& version handles it because the named expression ref is an lvalue.