Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are compilers not allowed to assume const-ref parameters will stay const?

For example:

https://godbolt.org/g/5eUkrx

void f(const int&);

void g1() {
    const int i = 42;

    if (i == 42) f(i);
    if (i == 42) f(i);
}

void g2() {
    int i = 42;

    if (i == 42) f(i);
    if (i == 42) f(i);
}

It seems like "f" mutating its argument should be UB, and therefore compilers should be allowed to assume it doesn't happen and optimize accordingly. Yet these two functions will produce different assembly.

I don't have a copy of the standard. Is this not guaranteed?

like image 438
Jeff M Avatar asked Mar 05 '18 18:03

Jeff M


1 Answers

It's perfectly fine according to the standard to cast a pointer-to-const to pointer-to-non-const in C++ and then modify it (albeit it is confusing), as long the value the pointer points to wasn't declared as const. In fact, C++ provides a keyword to do such a cast, const_cast.

For instance, this is fine.

int a = 2;
const int* b = &a;
*const_cast<int*>(b) = 4;

But this isn't as a memory location to which pointer points to is const.

const int a = 2;
const int* b = &a;
*const_cast<int*>(b) = 4;

Compiler in your example has to assume that a called function could possibly do that as it knows nothing about it, and prepare for such a situation.

like image 111
Konrad Borowski Avatar answered Oct 09 '22 14:10

Konrad Borowski