Whats the significance of return by reference?

后端 未结 11 1239
既然无缘
既然无缘 2021-02-13 00:15

In C++,

function() = 10;

works if the function returns a variable by reference.

What are the use cases of it?

11条回答
  •  北荒
    北荒 (楼主)
    2021-02-13 01:09

    The commonest case is to implement things like operator[].

    struct A {
        int data[10];
        int & operator[]( int i ) {
             return data[i];
        }
    };
    

    Another is to return a big object from a class via an accesor function:

    struct b {
        SomeBigThing big;
        const SomeBigThing & MyBig() const {
             return big;
        }
    };
    

    in order to avoid the copying overhead.

提交回复
热议问题