Sometimes the initialization of a const value is complex and needs some extra code:
int value{default_value}; // initialize some defaults
if (checkSomeSophisticatedConditions)
{
value = 8;
}
// use value
DoSomething(value);
// Since the value is determined at runtime, the only way to keep it unchanged is to write a function or to use another variable like this:
const int const_value {value};
value = 10;// This is valid
But actually in the business code the value should be const and the application should not change it’s value.
Using a second const value initialized by the non const value ist quiet easy but it needs some extra code and you will have a non const variable that might be used later by someone else. So it’s name is very important to descibe the usage.
Using a function separates the initialization logic from its usage. If you want to see what is going on here you have to look at two different places.
With C++11 we got lambdas and now can put a const value’s initialization into a closed scope next to it’s declaration.
const int const_value = [&]
{
int value {default_value};
if (checkSomeSophisticatedConditions)
{
value = 8;
}
return value;
}();
This issue is also discussed by Herb Sutter here.
You can test the code above here.