There are cases when I want a reference to an object but instead I get a copy. Here is an example:
std::pair<const std::string, int> foo("hello", 5);
const std::pair<std::string, int> & bar = foo;
std::cout << "foo: " << foo.first << " " << foo.second << std::endl;
std::cout << "bar: " << bar.first << " " << bar.second << std::endl;
foo.second = 7;
std::cout << "foo: " << foo.first << " " << foo.second << std::endl;
std::cout << "bar: " << bar.first << " " << bar.second << std::endl;
This produces:
foo: hello 5
bar: hello 5
foo: hello 7
bar: hello 5
So apparently a copy of foo
has been created while the syntax suggests (to me at least) that the programmer wanted a reference to it.
This violates the principle that a reference should be an alias to something. It would be great if somebody could explain what is going on and why.
(Note: I came across this here)