Is returning a reference ever a good idea?

前端 未结 2 1909
悲哀的现实
悲哀的现实 2021-01-24 03:22

We all know that returning a reference to a local variable is a bad idea. However, I\'m wondering if it\'s ever really a good idea to a return a reference at all and if it\'s po

2条回答
  •  梦毁少年i
    2021-01-24 03:51

    There are tons of good uses for returning a reference. One is, as you said, to emulate something like the native dereference operator:

    struct Goo
    {
        int & operator[](size_t i) { return arr[i]; }
        int & front()              { return arr[0]; }
    
        // etc.
    
    private:
        int * arr;
    };
    

    Another use case is when you return a reference to a thing that was passed in. The typical example is a chainable operation like <<:

    std::ostream & operator<<(std::ostream & os, Goo const & g)
    { 
        return os << g[3];
    }
    

    As a final example, here's a thread-safe global object:

    Goo & get_the_object()
    {
        static Goo impl;
        return impl;
    }
    

    References are an integral part of the language, and they may well be returned by a function call. As you said, it's important to understand the lifetime of objects, but that's always true and not a particular problem of returning references.

提交回复
热议问题