簡體   English   中英

“警告:並非所有控制路徑都返回值”是什么意思? (C ++)

[英]What does “warning: not all control paths return a value” mean? (C++)

我得到的確切警告是

warning C4715: "spv::Builder::makeFpConstant": not all control paths return a value

spv::Builder::makeFpConstant

Id Builder::makeFpConstant(Id type, double d, bool specConstant)
{
        assert(isFloatType(type));

        switch (getScalarTypeWidth(type)) {
        case 16:
                return makeFloat16Constant(d, specConstant);
        case 32:
                return makeFloatConstant(d, specConstant);
        case 64:
                return makeDoubleConstant(d, specConstant);
        }

        assert(false);
}

誰能幫我?

好吧,警告消息確切說明了問題所在。

如果定義了NDEBUG (即, assert s被禁用)並且都不采用case s,則控制在任何return語句之前到達函數的結尾(這導致未定義的行為)。

assert不算作控制流邏輯。 這只是“記錄”合同檢查。 在發行版本中,它甚至沒有發生! 僅是調試工具。

因此,如果標量類型寬度不是16、32或64,則留下的函數將忽略return語句。這意味着程序具有未定義的行為。 警告告訴您在所有情況下需要返回某些內容,即使您認為其他情況在運行時也不會發生。

在這種情況下,如果您通過了switch卻沒有返回,我可能會拋出異常-然后可以像處理其他任何異常情況一樣處理該異常。 如果您不希望發生異常,則可以選擇自己調用std::terminate (這是斷言最終將在調試版本中完成的工作)。

但是,終止是一種核選項,您實際上並不希望程序終止於生產中。 您希望它通過您現有的異常處理渠道發出正確的診斷消息,以便客戶報告錯誤時,他們可以說“顯然makeFpConstant獲得了一個意料之外的值”,並且您知道該怎么做。 而且,如果您不想將功能名稱泄露給客戶,那么您至少可以選擇一些只有您的團隊/企業知道的“秘密”失敗代碼(並在內部進行記錄!)。

不過,終止調試版本通常沒問題,因此也請保留該assert 或者只是依靠您現在擁有的異常,如果您不捕獲它,它將導致終止。

這可能是我編寫函數的方式:

Id Builder::makeFpConstant(
   const Id type,
   const double d,
   const bool specConstant
)
{
   assert(isFloatType(type));

   const auto width = getScalarTypeWidth(type);
   switch (width) {
      case 16: return makeFloat16Constant(d, specConstant);
      case 32: return makeFloatConstant(d, specConstant);
      case 64: return makeDoubleConstant(d, specConstant);
   }

   // Shouldn't get here!
   throw std::logic_error(
      "Unexpected scalar type width "
      + std::to_string(width)
      + " in Builder::makeFpConstant"
   );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM