Giao diện tối
12.4 — Lvalue references to const
🎯 Mục Tiêu Bài Học
- Nắm vững bản chất lý thuyết và cơ chế hoạt động của Lvalue references to const trong tiêu chuẩn ISO C++.
- Hiểu rõ cách máy tính tổ chức bộ nhớ (RAM, CPU registers) khi thực thi mã nguồn liên quan.
- Nhận biết các cạm bẫy lỗi kinh điển (Undefined Behavior, Memory Leak, Bug logic) và cách phòng tránh.
- Áp dụng các quy tắc thực hành tốt nhất (Best Practices) chuẩn công nghiệp và cập nhật C++20/C++23 hiện đại.
12.4 — Lvalue các tham chiếu to const
In the previous lesson ([12.3 -- Lvalue các tham chiếu](https://www.learncpp.com/cpp-tutorial/lvalue-các tham chiếu/)), we discussed how an lvalue tham chiếu can only bind to a modifiable lvalue. This means the following is illegal:
cpp
int main()
{
const int x { 5 }; // x is a non-modifiable (const) lvalue
int& ref { x }; // error: ref can not bind to non-modifiable lvalue
return 0;
}This is disallowed because it would allow us to modify a const biến (x) through the non-const tham chiếu (ref).
But what if we want to have a const biến we want to create a tham chiếu to? A normal lvalue tham chiếu (to a non-const value) won’t do.
Lvalue tham chiếu to const
By using the const keyword when declaring an lvalue tham chiếu, we tell an lvalue tham chiếu to treat the object it is referencing as const. Such a tham chiếu is called an lvalue tham chiếu to a const value (sometimes called a tham chiếu to const or a const tham chiếu).
Lvalue các tham chiếu to const can bind to non-modifiable lvalues:
cpp
int main()
{
const int x { 5 }; // x is a non-modifiable lvalue
const int& ref { x }; // okay: ref is a an lvalue reference to a const value
return 0;
}Because lvalue các tham chiếu to const treat the object they are referencing as const, they can be used to access but not modify the value being referenced:
cpp
#include <iostream>
int main()
{
const int x { 5 }; // x is a non-modifiable lvalue
const int& ref { x }; // okay: ref is a an lvalue reference to a const value
std::cout << ref << '\n'; // okay: we can access the const object
ref = 6; // error: we can not modify an object through a const reference
return 0;
}Initializing an lvalue tham chiếu to const with a modifiable lvalue
Lvalue các tham chiếu to const can also bind to modifiable lvalues. In such a case, the object being referenced is treated as const when accessed through the tham chiếu (even though the underlying object is non-const):
cpp
#include <iostream>
int main()
{
int x { 5 }; // x is a modifiable lvalue
const int& ref { x }; // okay: we can bind a const reference to a modifiable lvalue
std::cout << ref << '\n'; // okay: we can access the object through our const reference
ref = 7; // error: we can not modify an object through a const reference
x = 6; // okay: x is a modifiable lvalue, we can still modify it through the original identifier
return 0;
}In the above program, we bind const tham chiếu ref to modifiable lvalue x. We can then use ref to access x, but because ref is const, we can not modify the value of x through ref. However, we still can modify the value of x directly (using the identifier x).
Thực hành tốt nhất (Best Practice)
Favor lvalue các tham chiếu to const over lvalue các tham chiếu to non-const unless you need to modify the object being referenced.
Initializing an lvalue tham chiếu to const with an rvalue
Perhaps surprisingly, lvalues các tham chiếu to const can also bind to rvalues:
cpp
#include <iostream>
int main()
{
const int& ref { 5 }; // okay: 5 is an rvalue
std::cout << ref << '\n'; // prints 5
return 0;
}When this happens, a temporary object is created and được khởi tạo with the rvalue, and the tham chiếu to const is bound to that temporary object.
Related content
We covered temporary đối tượng in lesson [2.5 -- Introduction to local phạm vi truy cập (scope)](https://www.learncpp.com/cpp-tutorial/introduction-to-local-phạm vi truy cập (scope)/).
Initializing an lvalue tham chiếu to const with a value of a different type
Lvalue các tham chiếu to const can even bind to values of a different type, so long as those values can be implicitly converted to the tham chiếu type:
cpp
#include <iostream>
int main()
{
// case 1
const double& r1 { 5 }; // temporary double initialized with value 5, r1 binds to temporary
std::cout << r1 << '\n'; // prints 5
// case 2
char c { 'a' };
const int& r2 { c }; // temporary int initialized with value 'a', r2 binds to temporary
std::cout << r2 << '\n'; // prints 97 (since r2 is a reference to int)
return 0;
}In case 1, a temporary object of type double is created and được khởi tạo with int value 5. Then const double& r1 is bound to that temporary double object.
In case 2, a temporary object of type int is created and được khởi tạo with char value a. Then const int& r2 is bound to that temporary int object.
In both cases, the type of the tham chiếu and the type of the temporary match.
Hiểu biết cốt lõi
If you try to bind a const lvalue tham chiếu to a value of a different type, the trình biên dịch will create a temporary object of the same type as the tham chiếu, khởi tạo it using the value, and then bind the tham chiếu to the temporary.
Also note that when we print r2 it prints as an int rather than a char. This is because r2 is a tham chiếu to an int object (the temporary int that was created), not to char c.
Although it may seem strange to allow this, we’ll see examples where this is useful in lesson [12.6 -- Pass by const lvalue tham chiếu](https://www.learncpp.com/cpp-tutorial/pass-by-const-lvalue-tham chiếu/).
Cảnh báo nguy hiểm
We normally assume that a tham chiếu is identical to the object it is bound to -- but this assumption is broken when a tham chiếu is bound to a temporary copy of the object or a temporary resulting from the conversion of the object instead. Any modifications subsequently made to the original object will not be seen by the tham chiếu (as it is referencing a different object), and vice-versa.
Here’s a silly example showing this:
cpp
#include <iostream>
int main()
{
short bombs { 1 }; // I can has bomb! (note: type is short)
const int& you { bombs }; // You can has bomb too (note: type is int&)
--bombs; // Bomb all gone
if (you) // You still has?
{
std::cout << "Bombs away! Goodbye, cruel world.\n"; // Para bailar la bomba
}
return 0;
}In the above example, bombs is a short and you is a const int&. Because you can only bind to an int object, when you is được khởi tạo with bombs, the trình biên dịch will implicitly convert bombs to an int, which results in the creation of a temporary int object (with value 1). you ends up bound to this temporary object rather than bombs.
When bombs is decremented, you is not affected because it is referencing a different object. So although we expect if (you) to evaluate to false, it actually evaluates to true.
If you would stop blowing up the world, that would be great.
Const các tham chiếu bound to temporary đối tượng extend the lifetime of the temporary object
Temporary đối tượng are normally destroyed at the end of the biểu thức in which they are created.
Given the câu lệnh const int& ref { 5 };, consider what would happen instead if the temporary object created to hold rvalue 5 was destroyed at the end of the biểu thức that initializes ref. Reference ref would be left dangling (referencing an object that had been destroyed), and we’d get hành vi không xác định (Hành vi không xác định (Undefined Behavior - UB) - UB) when we tried to access ref.
To avoid dangling các tham chiếu in such cases, C++ has a special rule: When a const lvalue tham chiếu is directly bound to a temporary object, the lifetime of the temporary object is extended to match the lifetime of the tham chiếu.
cpp
#include <iostream>
int main()
{
const int& ref { 5 }; // The temporary object holding value 5 has its lifetime extended to match ref
std::cout << ref << '\n'; // Therefore, we can safely use it here
return 0;
} // Both ref and the temporary object die hereIn the above example, when ref is được khởi tạo with rvalue 5, a temporary object is created and ref is bound to that temporary object. The lifetime of the temporary object matches the lifetime of ref. Thus, we can safely print the value of ref in the next câu lệnh. Then both ref and the temporary object go out of phạm vi truy cập (scope) and are destroyed at the end of the block.
Hiểu biết cốt lõi
Lvalue các tham chiếu can only bind to modifiable lvalues.
Lvalue các tham chiếu to const can bind to modifiable lvalues, non-modifiable lvalues, and rvalues. This makes them a much more flexible type of tham chiếu.
For advanced readers
Lifetime extension only works when a const tham chiếu is directly bound to a temporary. Temporaries returned from a hàm (even ones returned by const tham chiếu) are not eligible for lifetime extension.
We show an example of this in lesson [12.12 -- Return by tham chiếu and return by address](https://www.learncpp.com/cpp-tutorial/return-by-tham chiếu-and-return-by-address/).
For class type rvalues, binding a tham chiếu to a member will extend the lifetime of the entire object.
So why does C++ allow a const tham chiếu to bind to an rvalue anyway? We’ll answer that question in the next lesson!
Constexpr lvalue các tham chiếu Optional
When applied to a tham chiếu, constexpr allows the tham chiếu to be used in a hằng số biểu thức. Constexpr các tham chiếu have a particular limitation: they can only be bound to đối tượng with static duration (either globals or static locals). This is because the trình biên dịch knows where static đối tượng will be instantiated in memory, so it can treat that address as a compile-time hằng số.
A constexpr tham chiếu cannot bind to a (non-static) local biến. This is because the address of local các biến is not known until the hàm they are defined within is actually called.
cpp
int g_x { 5 };
int main()
{
[[maybe_unused]] constexpr int& ref1 { g_x }; // ok, can bind to global
static int s_x { 6 };
[[maybe_unused]] constexpr int& ref2 { s_x }; // ok, can bind to static local
int x { 6 };
[[maybe_unused]] constexpr int& ref3 { x }; // compile error: can't bind to non-static object
return 0;
}When defining a constexpr tham chiếu to a const biến, we need to apply both constexpr (which applies to the tham chiếu) and const (which applies to the type being referenced).
cpp
int main()
{
static const int s_x { 6 }; // a const int
[[maybe_unused]] constexpr const int& ref2 { s_x }; // needs both constexpr and const
return 0;
}Given these limitations, constexpr các tham chiếu typically don’t see much use.
mermaid
flowchart LR
subgraph STACK_MEMORY["Vùng Nhớ Ngăn Xếp (Stack)"]
VarA["Biến gốc: a\nĐịa chỉ: 0x7ffd01\nGiá trị: 100"]
PtrP["Con trỏ: ptr\nĐịa chỉ: 0x7ffd08\nGiá trị: 0x7ffd01"]
RefR["Tham chiếu: ref\nBí danh (Alias) của a\nCùng địa chỉ: 0x7ffd01"]
end
PtrP -->|Trỏ tới địa chỉ| VarA
RefR -.->|Đồng nhất với| VarACạm Bẫy Thực Chiến: Con Trỏ Lơ Lửng (Dangling Pointer) & UB
Tuyệt đối không giải phóng vùng nhớ mà con trỏ đang trỏ tới rồi tiếp tục truy cập nó, hoặc trả về tham chiếu/con trỏ tới một biến cục bộ trên Stack. Khi hàm kết thúc, biến cục bộ bị hủy và con trỏ sẽ trỏ vào vùng nhớ rác, dẫn đến Hành vi không xác định (Undefined Behavior) cực kỳ nguy hiểm!
Nâng Cấp C++ Hiện Đại: Thay Thế Con Trỏ Thô Bằng Smart Pointers
Trong C++ hiện đại (C++11 đến C++23), hãy hạn chế tối đa việc sử dụng con trỏ thô (T*) cùng các toán tử new/delete. Thay vào đó, hãy luôn ưu tiên:
std::unique_ptr<T>: Sở hữu độc quyền tài nguyên (Zero-overhead, tự động giải phóng RAII).std::shared_ptr<T>: Sở hữu chia sẻ tài nguyên có cơ chế đếm tham chiếu (Reference counting).std::span<T>(C++20) hoặcstd::string_view(C++17): Xem qua vùng nhớ mà không sở hữu, an toàn và tốc độ cực cao.
💡 Tóm Tắt Quy Tắc Vàng (Core Guidelines)
- Luôn hiểu rõ vòng đời và quyền sở hữu (Ownership) của dữ liệu trước khi viết code.
- Ưu tiên khởi tạo đồng nhất với dấu ngoặc nhọn
{}để ngăn chặn lỗi thu hẹp kiểu dữ liệu (Narrowing conversions). - Bật toàn bộ cờ cảnh báo
-Wall -Wextra -Wpedanticđể compiler giúp bạn phát hiện bug từ sớm!