A const reference is an alias that avoids copying while preventing modification through that access path. Returning a non-const reference to a private member exposes the object’s actual state: client code can change it accidentally. section 9.13
Protecting an accessor result
A Person accessor that returns std::string& lets name += "x" change the Person. Returning const std::string& preserves efficient access, while the compiler rejects mutation through the returned reference. section 9.13
Use const references when the data is read-only and copying is undesirable:
- Return a member as const std::string& when callers need efficient read access without permission to mutate the object. section 9.13
- Declare input-only string parameters as const references so callers’ data cannot be modified and fewer bytes are copied. section 11.6
- Treat references as aliases, not local copies; changing a non-const alias changes the referred-to object and can alter its intended semantics. section 9.13
Listing 9.33 Using constants to prevent mutations and improve performance
class Person {
private:
std::string name;
int age;
public:
Person(const std::string& name, int age) : name(name), age(age) {}
const std::string& getName() const { return name; } #1
int getAge() const { return age; }
};
int main() {
Person sam("Samantha", 26);
const std::string& name = sam.getName(); #2
// name += "x";
std::cout << name << " is " << sam.getAge() << " years old\n";
return 0;
}
Compare the unsafe Person accessor with its const-reference return and observe the compiler-protected read-only local alias. section 9.13
Listing 11.10 Using parameter types well
const std::string catenate(const std::string& a, const std::string& b, const
std::string& c) {
std::string combined(a);
// b[0] = '-'; #1
combined += b;
// c[0] = 'z';
combined += c; #2
return combined;
}
int main() {
std::string msg1 = "Hello";
std::string msg2 = ", ";
std::string msg3 = "world!";
std::cout << catenate(msg1, msg2, msg3) << '\n';
return 0;
}
See const references applied consistently to input-only catenate parameters, replacing ambiguous writable references and pointers. section 11.6
