Try to limit the scope of constant constraints

When transferring constant initialization, I often encounter area problems

try { const int value = might_throw(); } std::cout << value << "\n"; /* error, value out of scope */ 

I am currently using a temporary value as a workaround. Is there a better way to handle const situations - try {} ?

 int tmp; /* I'd rather have tmp const */ try { tmp = might_throw(); } catch (...) { /* do something */ } const int value = tmp; 
+7
source share
3 answers

Instead

 int tmp; /* I'd rather have tmp const */ try { tmp = might_throw(); } catch (...) { /* do something */ } const int value = tmp; 

You can do it:

 int int_value() { try { return might_throw(); } catch (...) { /* do something */ return the_something_value; } } int main() { int const value = int_value(); } 

Or, in C ++ 11 you can do

 int main() { int const value = []() -> int { try { return might_throw(); } catch (...) { /* do something */ return the_something_value; } } (); } 
+9
source

For me, this looks like a case for a function:

 int const value = []()->int { try { return might_throw(); } catch (...) { return come_up_with_a_value_differently(); } }(); 
+3
source
 try { const int value = might_throw(); std::cout << value << '\n'; } catch (...) { std::cout << "threw instead of giving me a value :(\n"; } 

try is an area block for a reason!

If you do a lot more than std::cout with value , then yes it gets a little messier. Then you have a choice:

  • const removal,
  • embracing all the logic that uses value in try or
  • initialization of a const int from the value returned by the int mightThrowWrapper(int default = 0) function int mightThrowWrapper(int default = 0) , which itself wraps try / catch and returns the default value upon throw. Then you have localized exception handling and const ness!
0
source

All Articles