__declspec(noreturn)的用法

來源:互聯網
上載者:User

__declspec(noreturn)的用法

飄飄白雲 2008.11.26 先來看noreturn在MSDN中的註解:

一個函數被 __declspec(noreturn)所約定,那麼它的含義是告訴編譯器,這個函數不會返回,其結果是讓編譯器知道呼叫慣例為 __declspec(noreturn)的函數之後的代碼不可到達。
如果編譯器發現一個函數有無傳回值的代碼分支,編譯器將會報C4715的警告,或者C2202的錯誤資訊。如果這個代碼分支是因為函數不會返回從而無法到達的話,可以使用約定 __declspec(noreturn)來避免上述警告或者錯誤。 
注意: 

將一個期望返回的函數約定為 __declspec(noreturn) 將導致未定義的行為。

 樣本: 

在下面的這個例子中,main函數沒有從else 分支返回,所以約定函數fatal為__declspec(noreturn)來避免編譯或警告資訊。

// noreturn2.cpp__declspec(noreturn) extern void fatal () {}int main() { if(1) return 1; else if(0) return 0; else fatal();}
 -----------------------------------------------------------另一個用途就是在自訂exception的時候,可以用 __declspec(noreturn)來約定throw函數,因而可以在拋出異常的時候,讓其後的語句不被執行。 樣本:
  1. // Exception
  2. class Exception {
  3. public:
  4.     virtual~Exception()
  5.     {
  6.     }
  7. };
  8. // Exception
  9. // LogicalError
  10. class LogicalError :
  11.     public Exception {
  12.     CStringW m_Message;
  13. public:
  14.     LogicalError(LPCWSTR msg) :
  15.     m_Message(msg)
  16.     {
  17.     }
  18.     virtual~LogicalError()
  19.     {
  20.     }
  21.     LPCWSTR GetMessage() const
  22.     {
  23.         return m_Message;
  24.     }
  25.     static void DECL_NORETURN Throw(LPCWSTR msg)
  26.     {
  27.         throw LogicalError(msg);
  28.     }
  29. };

在使用的時候,就可以達到在調用throw之後,位於throw語句之後代碼不會被執行。

 比如:LPCWSTR getString(FILE* fp){    if( fp == NULL) {        LogicalError::Throw(L"getString(FILE* fp):File handle fp is NULL!");    }        ......} 


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.