try块限制const变量的范围

Mic*_*ann 9 c++ exception

当包装常量的初始化时,我经常遇到范围问题

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

目前我使用临时值作为解决方法.有没有更好的方法来处理const-try {}情况?

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

Che*_*Alf 10

而不是你的

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

你可以这样做:

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

int main()
{
    int const value = int_value();
}
Run Code Online (Sandbox Code Playgroud)

或者,在C++ 11中,你可以做到

int main()
{
    int const value = []() -> int {
        try {
            return might_throw();
        }
        catch (...) {
            /* do something */
            return the_something_value;
        }
    } ();
}
Run Code Online (Sandbox Code Playgroud)