-1

I have this class in singleton.h:

class SingletonSample {
public:
     static SingletonSample& Instance();
     int DoSomething() const;
private:
     SingletonSample();
     ~SingletonSample();
     SingletonSample(const SingletonSample&) = delete;
     SingletonSample& operator=(const SingletonSample&) = delete;
     static SingletonSample* _instance;
}

And I have this implementation in singleton.cpp:

SingletonSample::SingletonSample() {}
SingletonSample::~SingletonSample() {}
SingletonSample& SingletonSample::Instance() {
    if(!_instance) _instance = new SingletonSample();
    return _instance;
}
int SingletonSample::DoSomething() const {
    return 20;
}

I have a compiler error when trying to return _instance.

I want to return a SingletonSample&, but my _instance is a pointer SingletonSample*.

I'm a beginner in C++ but as far as I understand, a reference to something is just the address to that something, while a pointer to something is just a pointer to that address.

I would like to return that address being pointed by the pointer, as a reference SingletonSample&.

However, I cannot manage to achieve that. How can I do this?

Matias Cicero
  • 21,834
  • 10
  • 67
  • 132

1 Answers1

6

A reference is not an address of an object. It is just an alias for one. You simply have to de-reference the pointer:

return *_instance;

This lets the reference refer to the object pointed at by _instance.

Note that the implementation can be greatly simplified:

SingletonSample& SingletonSample::Instance() {
  static SingletonSample instance;
  return instance;
}

Also note that singletons are generally considered a bad idea.

Community
  • 1
  • 1
juanchopanza
  • 210,243
  • 27
  • 363
  • 452