11

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

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

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

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

3 回答 3

10

而不是你的

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

你可以这样做:

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

int main()
{
    int const value = int_value();
}

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

int main()
{
    int const value = []() -> int {
        try {
            return might_throw();
        }
        catch (...) {
            /* do something */
            return the_something_value;
        }
    } ();
}
于 2012-11-12T12:10:34.570 回答
3

对我来说,这看起来像是一个函数的案例:

int const value = []()->int {
    try { return might_throw(); }
    catch (...) { return come_up_with_a_value_differently(); }
}();
于 2012-11-12T12:10:57.403 回答
0
try {
   const int value = might_throw();
   std::cout << value << '\n';
}
catch (...) {
   std::cout << "threw instead of giving me a value :(\n";
}

try是一个范围块是有原因的!

如果你做的远不止 a std::coutwith valuethen,是的,它会变得有点混乱。然后您可以选择:

  • 丢弃const,
  • 包含在,或_valuetry
  • 从本身包装 try/catch 并在 throw 时返回默认const int值的函数返回的值初始化 a 。int mightThrowWrapper(int default = 0)然后你就有了本地化的异常处理 const能力!
于 2012-11-12T12:08:35.927 回答