Is returning a reference ever a good idea?

前端 未结 2 1907
悲哀的现实
悲哀的现实 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: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

提交回复
热议问题