References
Quick Notes
Section titled “Quick Notes”Reference là alias cho object đã tồn tại. Dùng non-const reference để sửa object truyền vào. Dùng const reference để tránh copy object lớn nhưng vẫn không cho sửa.
Syntax
Section titled “Syntax”int x = 10;int& ref = x;const std::string& name = getName();Example
Section titled “Example”#include <string>
void trimLeft(std::string& s){ while (!s.empty() && s.front() == ' ') { s.erase(0, 1); }}
int lengthOf(const std::string& s){ return static_cast<int>(s.size());}Passing Style
Section titled “Passing Style”| Style | Use |
|---|---|
T value | Copy nhỏ, cần sở hữu bản riêng |
T& value | Cần sửa object |
const T& value | Object lớn, chỉ đọc |
T&& value | Move/perfect forwarding |
Common Mistakes
Section titled “Common Mistakes”- Trả reference tới biến local.
- Dùng non-const reference khi hàm không sửa dữ liệu.
- Tưởng reference có thể rebind sang object khác.
Search Keywords
Section titled “Search Keywords”references tham chiếu const reference pass by reference alias rebind