Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constant, but only for the remainder of this scope

Tags:

c++

I sometimes encounter cases where it would make sense for a variable to be const, but only for the latter part of its scope. For example, the first part of a block might set the value, and readability of the rest might be improved if it were clear that we were "done" setting that variable -

void foo() {
  int n;
  // Do things that result in initialization of n

  freeze n;  // Imaginary construct that declares "n" const for rest of scope

  // Later steps that depend on 'n' but do not change it
}

Is there any C++ idiom that captures this pattern? Of course the latter part of the block could be moved to a separate function, but can it be done without moving things around as much?

like image 629
gcbenison Avatar asked Dec 02 '15 00:12

gcbenison


1 Answers

Your "freeze" code could look like:

const int &refN = n;

and then you use refN instead of n. You could switch the names around.

There are more complicated solutions but you really have to ask yourself whether the gain is worth the pain. If your function is so complicated that you can't see at a glance whether you modified n then you need to refactor your code.


For example, to hide n you could do:

{
const int &_tmp = n;
const int &n = _tmp;

// rest of code

}

but you have to ask yourself if it is worth it. Whoever reads the code after you will wonder what you were smoking.


Another option is for your function to be:

const int n = setup_n();

where you offload the logic to another function, or a lambda:

const int n = [](){
   // ...logic...
   return finalized_value;
}();
like image 113
M.M Avatar answered Nov 15 '22 11:11

M.M