Literal initialization for const references

前端 未结 3 984
猫巷女王i
猫巷女王i 2020-11-28 10:03

How does the following code work in C++? Is it logical?

const int &ref = 9;
const int &another_ref = ref + 6;

Why does C++ allow l

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 10:52

    So you can write code like this:

    void f( const string & s ) {
    }
    
    f( "foobar" );
    

    Although strictly speaking what is actually happening here is not the literal being bound to a const reference - instead a temprary string object is created:

    string( "foobar" );
    

    and this nameless string is bound to the reference.

    Note that it is actually quite unusual to create non-parameter reference variables as you are doing - the main purpose of references is to serve as function parameters and return values.

提交回复
热议问题