Domanda

class Foo{
    void operator=(const Foo&){};   
public:
    Foo(){};
};

Foo& fooRef(){
    static Foo aFoo;
    return aFoo;
}
int main() {
    Foo &foo = fooRef();
    return 0;
}

This code works properly without issuing any errors. As soon as I change the body of the main to:

int main(){
    Foo &foo; 
    foo = fooRef();
    return 0;
}

the compiler tries to use the operator= and hence complains. So my first question is: why does it make a difference?

The way I arrived to this fact is that I am doing unit testing using CPPunit where I have to test a singleton class that has the signature of getInstance() being Singleton& getInstance(). To do my testing I am trying to init an instance in singleton in the TestSingleton class. Hence having:

class TestSingleton{
...
private:
    Singleton &instance;
};


void TestSingleton::setUp(){
    this->instance = Singleton::getInstance();
}

Which having the above example issues an error (as the operator= is declared private, and if it would not be, it is obvious I do not wont it to be invoked). So the second question is: how would I avoid this and get an instance of singleton in my TestSingleton class?

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top