Pass the same object as a constant and non-constant reference

The following code compiles with g ++ v4.8.1 and outputs 45, but is its compilation guaranteed based on the standard? Will 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 is nothing wrong with the definition of a function, but when calling testwith the same object, vI was somewhat expecting a warning that I was passing one object as a const- const.

+4
source share
3 answers

No problem, because the compiler treats these two parameters as different links. 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;
+5
source

, . const, const .

:

int i = 42;
const int& const_ref = i;
int& ref = i;

, .

, , , , .

+2

, . . , , , const- , , const? ( , , , , )

, , . const. const , , .

+2
source

All Articles