Whats the significance of return by reference?

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

    The named parameter idiom is a another use case. Consider

    class Foo
    {
    public:
        Foo(
            int lions,
            float tigers,
            double bears,
            std::string zookeeper
        );
    };
    

    users of this class need to remember the position of each parameter

    Foo foo( 1, 2.0, 5, "Fred" );
    

    which can be non-obvious without looking at the header. Compared to a creator class like so

    class CreateFoo
    {
    friend class Foo;
    public:
        CreateFoo();
    
        CreateFoo& lions(int lions) {
            _lions = lions;
             return *this;
        }
    
        CreateFoo& tigers(float tigers) {
            _tigers = tigers;
            return *this;
        }
    
        CreateFoo& bears(double bears) {
            _bears = bears;
            return *this;
        }
    
        CreateFoo& zookeeper(const std::string& zookeeper) {
            _zookeeper = zookeeper;
            return *this;
        }
    
    private:
        int _lions;
        float _tigers;
        double _bears;
        std::string _zookeeper;
    };
    

    which can then be used by clients like so

    Foo foo = CreateFoo().
        lions(1).
        tigers(2.0).
        zookeeper("Fred").
        bears(5)
        ;
    

    assuming Foo has a constructor taking a const CreateFoo&.

提交回复
热议问题