Is returning a reference ever a good idea?

£可爱£侵袭症+ 提交于 2019-12-02 04:35:47

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!