Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass same object as const and non-const reference

Tags:

c++

constants

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.

like image 521
glinka Avatar asked Dec 19 '22 12:12

glinka


2 Answers

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;
like image 172
Vlad from Moscow Avatar answered Dec 31 '22 02:12

Vlad from Moscow


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.

like image 41
Drax Avatar answered Dec 31 '22 01:12

Drax