Reference initialization in C++

前端 未结 6 1576
挽巷
挽巷 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:52

    Uninitialized references cannot exist.

    Unfortunately funny things can be done during initialization. You could have also written

    const int& a = foobar(a) ? 1 : 2;
    

    or for the matter

    const int& a = a;
    

    I suppose as the compiler proceeds from left to right, a is indeed in scope on the right side, so technically you should be able to use it and at best it can warn:

    "ComeauTest.c", line 9: warning: variable "a" is used before its value is set

      const int& a = foobar(a) ? 1 : 2;
                            ^
    

    Naturally this can only result in undefined behavior as with using any uninitialized variable.

    Your example is fine, since you don't use the reference before it has been initialized.

提交回复
热议问题