Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try block limits scope of const variable

Tags:

c++

exception

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;
like image 974
Micha Wiedenmann Avatar asked Nov 12 '12 12:11

Micha Wiedenmann


2 Answers

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;
        }
    } ();
}
like image 177
Cheers and hth. - Alf Avatar answered Nov 04 '22 09:11

Cheers and hth. - Alf


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(); }
}();
like image 33
Dietmar Kühl Avatar answered Nov 04 '22 10:11

Dietmar Kühl