Is returning a reference ever a good idea?

前端 未结 2 1908
悲哀的现实
悲哀的现实 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条回答
  • 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.

    0 讨论(0)
  • 2021-01-24 03:55

    Personally, I like returning references to static variables when I want to implement the Singleton pattern

    SomeClass& getTheSingleton()
    {
        static SomeClass theInstance;
        return theInstance;
    }
    

    I dont have to write any logic involving whether or not some pointer is initialized, and it gives me some control over the order of static initialization

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