why is the return type of getinstance methods the return type of references?

Just a few more additions:

The return type doesn’t have to be a reference, but since the destructor of the class you are returning is private, any function (not this specific one) which returns an object of that type cannot return the actual object.

This is because the caller cannot make a copy of that object. When passed by value, a copy of the object is created, and returned back (there are more optimizations on this but this is the simplest idea). The caller then destroys that object when it gets out of scope, if it is private, the caller cannot.

One more quick note on returning references, when you return a reference, the caller is not responsible for the lifetime of the object. If you destroy the returned object, before the caller is done with it, you might end up in an access violation to uninitialized (destroyed) memory. In your example, this is not possible because the returned object is a static object which will live until the end of the application, so this pattern is good if that is your intention, and as also mentioned in some comments, it is called the singleton pattern.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top