Reference initialization in C++

前端 未结 6 1581
挽巷
挽巷 2021-01-25 01:06

Greetings, everyone!

Examining my own code, I came up to this interesting line:

const CString &refStr = ( CheckCondition() ) ? _T(\"foo\") : _T(\"bar         


        
6条回答
  •  感情败类
    2021-01-25 01:47

    Simpler example: const int x = foo();

    This constant too has to be initialized, and for that foo() needs to be called. That happens in the order necessary: x comes into existance only when foo returns.

    To answer your additional questions: If foo() would throw, the exception will be caught by a catch() somewhere. The try{} block for that catch() surrounded const int x = foo(); obviously. Hence const int x is out of scope already, and it is irrelevant that it never got a value. And if there's no catch for the exception, your program (including const int x) is gone.

    C++ doesn't have random goto's. They can jump within foo() but that doesn't matter; foo() still has to return.

提交回复
热议问题