Is it possible to tell the compiler that a value referenced by a pointer/reference is not modified over function calls?

Viewed 63
void g();

int f(const int &x) {
  int y = x;
  g();
  return x + y;
}

Here, the value in x has to be loaded twice before and after g() because g is allowed to modify the value referenced by x.

You can do an explicit load to avoid the problem.

int f(const int &rx) {
  int x = rx;
  int y = x;
  g();
  return x + y;
}

But C++ has developed in a way that you don't have to write down such details and still have performant code.

Is there a way to tell the compiler in the declaration of x, that the value being referenced will not change over external function calls?

1 Answers

There is no way to mark a function as not modifying x and from the shown code it is not clear that is even the case. Consider this source:

void g();

int f(const int &x) {
  int y = x;
  g();
  return x + y;
}

int t;

void g() { ++t; }

int main() {
    f(t);
}

Unless the compiler sees the definition of g and can see that x can not be modified by it there is no way to avoid the 2 loads. Many compilers won't even try unless g is inlined.

Note: gcc/clang have attribute pure to mark functions without side effects:

[[gnu::pure]] void g();

But a pure function returning void means it will never ever get called. Void functions without side effect make no sense.

Related