References cannot be neither default initialized nor re-seated. They have to refer to an existing object from the beginning. They are just aliases for another object.
So the second question is: how would I avoid this and get an instance of singleton in my
TestSingleton
class?
You can initialize reference members using the constructor initialization list:
class TestSingleton{
...
TestSingleton(Singleton& s) : instance(s) {}
private:
Singleton &instance;
};
If you find that you need to be able to default initialize and then re-seat a "reference", you should use a pointer or an optional type instead (see boost::optional
for example). But in this particular case, since you are dealing with a singleton, there is actually no need to store a reference to it. You can simply use Singleton::getInstance()
whenever you need it.