Phần 1
1. Problem It Solves
C++ programs often need to access the same object from several places without making unnecessary copies. The type system should also communicate whether:
the object may be changed through a particular name;
an object is required or optional;
a function works with the caller's original object; and
an address may later be redirected to another object.
const, pointers, and lvalue references express these constraints directly in
function signatures and variable declarations.
Phần 2
2. Prerequisites
Before this lesson, you should know:
how to define a
.cppfile andmain();how to compile in C++11 mode;
basic variables such as
intanddouble; andthe address-of operator
&and dereference operator*.
Phần 3
3. Core Idea
A normal variable owns its stored value.
A pointer stores the address of an object. It can represent “no object” with
nullptr, and a non-const pointer can later point to another compatible object.
An lvalue reference is another name for an existing object. It must be initialized when declared and cannot later be rebound to a different object.
const prevents modification through the name, pointer, or reference on which
it appears. It does not necessarily make the underlying object globally
immutable because another non-const access path may still change that object.
Phần 4
4. Minimal Syntax
double price = 189.10;
double* price_ptr = &price;
double& price_ref = price;
const double& read_only_price = price;Use *price_ptr to access the object addressed by a pointer. A reference is
used with the same syntax as the original variable.
Phần 5
5. Reading const Pointer Declarations
The position of const changes what may be modified:
double price = 189.10;
double other_price = 189.14;
const double* pointer_to_const = &price;
double* const const_pointer = &price;
const double* const const_pointer_to_const = &price;const double*means a pointer to a read-onlydouble. The pointer may be redirected, but the value cannot be changed through that pointer.double* constmeans a fixed pointer to a mutabledouble. The pointer cannot be redirected, but the value may be changed through it.const double* constmeans neither the pointer nor the value may be changed through that declaration.
For example:
pointer_to_const = &other_price; // Valid.
*const_pointer = 189.12; // Valid.Phần 6
6. How References and Pointers Work
&price obtains the address of price. A pointer stores that address, and
*price_ptr accesses the object at the stored address.
The declaration below binds price_ref to price:
double& price_ref = price;Assigning through price_ref changes price. A later statement such as
price_ref = other_price copies the value of other_price into price; it
does not rebind the reference.
A const double& also refers to the original object, but code using that
reference cannot modify the object through the reference. For large objects,
this commonly avoids a copy while preserving read-only access.
Phần 7
7. Lifetime and Validity
Pointers and references do not own the objects they refer to. The referenced object must remain alive and at a stable address for the entire use.
Production code must check:
a pointer is not
nullptrbefore dereferencing it;the pointed-to or referenced object has not been destroyed;
a container operation has not invalidated an address or reference; and
an asynchronous callback does not outlive the captured object.
For example, growing a std::vector may reallocate its storage and invalidate
pointers and references to its elements. Erasing an element can also invalidate
access paths to that element and later elements.
Phần 8
8. Common Mistakes
Dereferencing
nullptrcauses undefined behavior.Reading through an uninitialized pointer may access an invalid address.
Returning a pointer or reference to a local variable creates a dangling access after the function returns.
Assigning to a reference changes the referred-to object; it does not rebind the reference.
Confusing
const double*withdouble* constgrants or removes the wrong mutation capability.Keeping a pointer or reference across a container reallocation may leave it dangling.
Phần 9
9. Trading Use Case
A quote-processing function can receive a quote through a const reference,
avoiding a copy and preventing accidental modification. A pointer can represent
an optional selected price level. A non-const reference can update an existing
volume counter directly.
Before retaining any of these access paths, the program must define who owns the quote and whether order-book updates, container growth, erasure, or thread handoff can invalidate its address.
Phần 10
10. Key Takeaways
Use
constto express read-only access through a specific path.Use a reference when a valid object must exist.
Use a pointer when “no object” or reselection is meaningful.
A pointer or reference does not extend an ordinary object's lifetime.
Check lifetime and invalidation rules before storing either one.
Never dereference a pointer before establishing that it is valid.
Phần 11
11. Self-Check Questions
Why can a pointer be
nullptrwhile a valid reference cannot?What changes when assigning through a non-const lvalue reference?
What is the difference between
const double*anddouble* const?Why can growing a
std::vectorinvalidate a pointer to one of its elements?When should an API prefer
const T&overT*?
Mã mẫu hoàn chỉnh
cpp11/31_const pointer lvalue reference/main.cpp
#include <iostream>
void print_quote(const double& bid, const double& ask) {
// const references read the original values without copying or
// modifying them.
std::cout << "Bid: " << bid << '\n';
std::cout << "Ask: " << ask << '\n';
}
void add_volume(int& volume, int added_volume) {
// A non-const reference can modify the original variable.
volume += added_volume;
}
int main() {
const char* const symbol = "AAPL";
double bid = 189.10;
double ask = 189.14;
int bid_volume = 500;
const double* selected_price = &bid;
double& price_alias = bid;
std::cout << "Symbol: " << symbol << '\n';
print_quote(bid, ask);
std::cout << "Selected price: " << *selected_price << '\n';
price_alias = 189.12; // Changes bid because price_alias refers to bid.
add_volume(bid_volume, 100);
// A pointer-to-const can be redirected, but it cannot modify the price.
selected_price = &ask;
std::cout << "Updated bid: " << bid << '\n';
std::cout << "Updated bid volume: " << bid_volume << '\n';
std::cout << "Pointer now selects ask: " << *selected_price << '\n';
const double& read_only_ask = ask;
std::cout << "Read-only ask reference: " << read_only_ask << '\n';
return 0;
}
Tự kiểm tra · không chấm điểm
Bạn đã hiểu những điểm nào?
Bài này chưa có danh sách tự kiểm tra trong nguồn.