Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, can I declare a reference so as to indicate that nothing will ever modify it?

If I do

typedef void Cb();

int foo(int const& a, Cb cb) {
  int x = a;
  cb();
  return x - a;
}

and compile with g++ -O3 -save-temps -c foo.cpp, I see that the subtraction is preserved, whereas if cb(); is commented out, the entire function optimizes to

xorl    %eax, %eax

Is there something I can do to the specification of the parameter a so that the subtraction will be optimized out regardless of the call to cb(), and without forcing a to be a unique reference (ie, that it may be referred to elsewhere, but that via none of those references will it be modified)?

like image 321
Owen Avatar asked Dec 04 '14 16:12

Owen


People also ask

Can you set a reference to null?

A reference isn't supposed to be null. The variable must be initialized to a non-null value. The variable can never be assigned the value null . The compiler issues a warning when code assigns a maybe-null expression to a variable that shouldn't be null.

How do you declare a reference variable in C?

Master C and Embedded C Programming- Learn as you go Reference variable is an alternate name of already existing variable. It cannot be changed to refer another variable and should be initialized at the time of declaration and cannot be NULL. The operator '&' is used to declare reference variable.

Can we modify reference variable?

You cannot reassign a reference.

Why do we usually not use references in C?

Conceptually, C has references, since pointers reference other objects. Syntactically, C does not have references as C++ does. Wrong, conceptually pointers and references are absolutely different. Pointer is an algebraic data type of null and a reference.


2 Answers

There's the __restrict extension, you can try this on gcc.godbolt.org:

typedef void Cb();

int foo(const int & __restrict a, Cb cb) {
  int x = a;
  cb();
  return x - a;
}

Curiously, only clang does the optimization, gcc doesn't do it.


Notice that restrict-like aliasing is being considered to be part of the C++ standard:

  • N3988: Towards restrict-like aliasing semantics—Finkel, Tong, Carruth, Nelson, Vandevoorde, Wong

Maybe in the future you can do it by the standard.

like image 158
pepper_chico Avatar answered Sep 19 '22 14:09

pepper_chico


Doing the suggested optimization would be incorrect because the rest of the code might be:

static int var;

void func()
{
    var++;
}

// ...
foo(var, func);

I'm not aware of any compiler-specific attribute you can set to say that cb() will not modify a.

like image 33
M.M Avatar answered Sep 20 '22 14:09

M.M