I just found an interesting case: I passed an object by const reference
and still I was able to modify its member (which happens to be an lvalue reference
). Following is an example:
#include <iostream>
#include <string>
struct PersonRef
{
PersonRef(std::string& name_) : _name(name_) {}
std::string& _name; // <==== IMPORTANT: it is a reference
};
void testRef(const PersonRef& pr) {
std::string& name = pr._name; // binding to lvalue reference? How does it even compile?
name = "changed!";
}
int main() {
std::string name = "trivial_name";
PersonRef pr{name};
std::cout << pr._name << "\n"; // prints: trivial_name
testRef(pr);
std::cout << pr._name << "\n"; // prints: changed!
}
I used to think that if the parameter is passed by const ref
, then object is immutable but this doesn't appear to be the case here. Could someone please explain this? Thanks!