try block limits scope of const variable
c++, exception
Solution
Instead of your
int tmp; /* I'd rather have tmp const */
try {
tmp = might_throw();
}
catch (...) {
/* do something */
}
const int value = tmp;
you can do this:
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;
}
} ();
}
Problem
When wrapping initializations of a constant I frequently run into scope issues ``` try { const int value = might_throw(); } std::cout << value << "\n"; /* error, value out of scope */ ``` Currently I use a temporary value as a workaround. Is there a better way to deal with `const` - `try {}` situations? ``` int tmp; /* I'd rather have tmp const */ try { tmp = might_throw(); } catch (...) { /* do something */ } const int value = tmp; ```