Whats the significance of return by reference?

后端 未结 11 1246
既然无缘
既然无缘 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.

    0 讨论(0)
  • 2021-02-13 01:17

    std::vector has operator[] which would not allow vec[n] = m otherwise.

    0 讨论(0)
  • 2021-02-13 01:17

    You can also achieve method chaining (if you so desire) using return by reference.

    class A
    {
    public:
        A& method1()
        {
            //do something
            return *this;   //return ref to the current object
        }
        A& method2(int i);
        A& method3(float f);  //other bodies omitted for brevity
    };
    
    int main()
    {
        A aObj;
        aObj.method1().method2(5).method3(0.75);
    
        //or use it like this, if you prefer
        aObj.method1()
            .method2(5)
            .method3(0.75);
    }
    
    0 讨论(0)
  • 2021-02-13 01:18

    It can be usefull when implementing accessors

    class Matrix
    {
       public:
          //I skip constructor, destructor etc
    
          int & operator ()(int row, int col)
          {
             return m_arr[row + col * size];
          }
    
       private:
          int size;
          int * m_arr;
    }
    
    Matrix m(10);
    m(1,0) = 10;  //assign a value to row 1, col 0
    
    0 讨论(0)
  • 2021-02-13 01:21

    SO screwed up my answer

    You don't even need to return a reference:

    struct C { };
    
    C f() {
      return C();
    }
    
    int main() {
      C a;
      f() = a;  // compiles fine
    }
    

    Because this behavior is quite surprising, you should normally return a const value or a const reference unless the user has a sensible intent to modify the result.

    0 讨论(0)
提交回复
热议问题