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;
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;
}
} ();
}
To 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(); }
}();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With