Whats the significance of return by reference?

后端 未结 11 1223
既然无缘
既然无缘 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:05

    In case you have a class that contains another structure, it can be useful to directly modify the contained structure:

    struct S
    {
        int value;
    };
    
    class C
    {
        public:
    
            S& ref() { return m_s; }
    
        private:
    
            S m_s;
    };
    

    Allows you to write something like:

    void foo()
    {
        C c;
    
        // Now you can do that:
    
        c.ref().value = 1;
    }
    

    Note: in this example it might be more straightforward to directly make m_s public rather than returning a reference.

提交回复
热议问题