Skip to content

References

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.

int x = 10;
int& ref = x;
const std::string& name = getName();
#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());
}
StyleUse
T valueCopy nhỏ, cần sở hữu bản riêng
T& valueCần sửa object
const T& valueObject lớn, chỉ đọc
T&& valueMove/perfect forwarding
  • 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.

references tham chiếu const reference pass by reference alias rebind