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;