_ Declspec (noreturn) Usage
Floating white clouds 2008.11.26 first look at the annotation of noreturn in msdn:
A function is
_ Declspec (noreturn)As agreed, it means to tell the compiler that this function will not be returned, and the result is to let the compiler know that the call convention is
_ Declspec (noreturn)The code after the function is not reachable.
If the compiler finds that a function has a code branch with no return value, the compiler reports a c4715 warning or c2202 error message. If this code branch cannot be reached because the function does not return, you can use the Convention.
_ Declspec (noreturn)To avoid the above warnings or errors.
| Note: |
Convention on a function to be returned_ Declspec (noreturn)Will lead to undefined behavior. |
Example:
In the following example, the main function is notElseBranch return, so the agreed FunctionFatalIs_ Declspec (noreturn)To avoid compilation or warning.
// noreturn2.cpp__declspec(noreturn) extern void fatal () {}int main() { if(1) return 1; else if(0) return 0; else fatal();}----------------------------------------------------------- Another purpose is to use
_ Declspec (noreturn)To define the throw function. Therefore, when an exception is thrown, the subsequent statement is not executed. Example:
- // Exception
- Class exception {
- Public:
- Virtual ~ Exception ()
- {
- }
- };
- // Exception
- // Logicalerror
- Class logicalerror:
- Public exception {
- Cstringw m_message;
- Public:
- Logicalerror (lpcwstr MSG ):
- M_message (MSG)
- {
- }
- Virtual ~ Logicalerror ()
- {
- }
- Lpcwstr getmessage () const
- {
- Return m_message;
- }
- Static void decl_noreturn throw (lpcwstr MSG)
- {
- Throw logicalerror (MSG );
- }
- };
In use, the code will not be executed after the throw statement is called.
For example: lpcwstr getstring (File * FP) {If (FP = NULL) {logicalerror: Throw (L "getstring (File * FP): file handle FP is null! ");}......}