The following code compiles with g++ v4.8.1 and outputs 45
, but is its compilation guaranteed based on the standard? Would other compilers complain?
#include <iostream>
#include <vector>
void test(const std::vector<int>& a, std::vector<int>& b) {
b[0] = 45;
}
int main() {
std::vector<int> v(1,0);
test(v, v);
std::cout << v[0] << std::endl;
}
I understand that there's nothing inherently wrong with the function definition, but when calling test
with the same object, v
, I somewhat expected a warning that I was passing a single object as both a const
and non-const
reference.
There is no problem becuase the compiler consideres these two parameters as different references. To understand the code consider the following example
int i = 10;
const int &cr = i;
int &r = i;
r = 20;
std::cout << cr << std::endl;
There is no reason this shouldn't compile. Your vector is not const, you can then use it in a const or mutable context.
The same way this works :
int i = 42;
const int& const_ref = i;
int& ref = i;
Wether you bind the same object or not does not have any incidence here.
You should look at this as if there was a lion in a zoo, the visitors behind windows cannot touch him whereas the trainers can feed him, but it is still the same lion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With