2

lvlですenum class

switch(lvl)
{
case LogLevel::Trace:
    return "Trace";
case LogLevel::Debug:
    return "Debug";
case LogLevel::Info:
    return "Info";
case LogLevel::Warning:
    return "Warning";
case LogLevel::Error:
    return "Error";
case LogLevel::Fatal:
    return "Fatal";
default:
    assert(0 && "Unhandled LogLevel in LevelToStr"); return "???";      // This one?
    throw std::invalid_argument( "Unhandled LogLevel in LevelToStr" );  // or this one?
}

コンセンサスはdefaultそこにあるべきですが、関連する質問の意見は、それが何をすべきかについて分かれています。全体をクラッシュしますか?現在のスレッドをクラッシュしますか? 例外を適切に処理しますか?

両陣営はコメントでいくつかの議論を提示していますが、議論は完全に決定的なものではありません.

どちらを使用すべきか、またはどの条件で使用すべきか、誰かが包括的な答えを提示できますか?

4

1 に答える 1

2

システムの要件に完全に依存します。

この場合、実際には使用しない方がよいと主張しますdefault:。これを省略した場合、コンパイル時にケースを見逃した場合に役立つ警告が表示されます。-Werror を指定してコンパイルすると、警告を修正するまで、プログラムはコンパイルに失敗します。

void handle_something(LogLevel lvl)
{
    switch(lvl)
    {
    case LogLevel::Trace:
        return "Trace";
    case LogLevel::Debug:
        return "Debug";
    case LogLevel::Info:
        return "Info";
    case LogLevel::Warning:
        return "Warning";
    case LogLevel::Error:
        return "Error";
    case LogLevel::Fatal:
        return "Fatal";
    // note: no default case - better not to suppress the warning
    }

    // handle the default case here

    // ok, so now we have a warning at compilation time if we miss one (good!)
    // next question: can the program possibly continue if this value is wrong?
   // if yes...
   return some_default_action();

   // ... do we want debug builds to stop here? Often yes since
   // ... this condition is symptomatic of a more serious problem
   // ... somewhere else

   std::assert(!"invalid log level");

   // ...if no, do we want to provide information as to why
   // ... which can be nested into an exception chain and presented
   // ... to someone for diagnosis?

   throw std::logic_error("invalid error level: " + std::to_string(static_cast<int>(lvl));

  // ... or are we in some mission-critical system which must abort and
  // ... restart the application when it encounters a logic error?

  store_error_in_syslog(fatal, "invalid log level");
  std::abort();
}
于 2016-05-09T10:03:15.073 に答える