Greetings, everyone!
Examining my own code, I came up to this interesting line:
const CString &refStr = ( CheckCondition() ) ? _T("foo") : _T("bar");
Now I am completely at a loss, and cannot understand why it is legal. As far as I understand, const reference must be initialized, either with r-value or l-value. Uninitialized references cannot exist. But ()? operator executes a CheckCondition() function before it assigns value to the reference. I can see now, that while CheckCondition() is executed, refStr exists, but still not initialized. What will happen if CheckCondition() will throw an exception, or pass control with a goto statement? Will it leave the reference uninitialized or am I missing something?
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()wouldthrow, the exception will be caught by acatch()somewhere. Thetry{}block for thatcatch()surroundedconst int x = foo();obviously. Henceconst int xis out of scope already, and it is irrelevant that it never got a value. And if there’s nocatchfor the exception, your program (includingconst int x) is gone.C++ doesn’t have random
goto‘s. They can jump withinfoo()but that doesn’t matter;foo()still has to return.