I have looked at this thread on singleton class implementation, but not clear on how to use it in practice. To make the context more concrete, say I have a input stream std::istream
instance that many different class need to access, but instead of passing it in for each class constructor, I am thinking of using a singleton class Connection
to wrap this info. So a client can just call:
Connection.getInstance().get_input_stream();
My questions are two fold: (1) is this a proper use of singleton class (2) on implementing this, I have tried something like this:
class Connection {
public:
static Connection& getInstance() {
static Connection instance; // Guaranteed to be destroyed
return instance;
}
std::istream& get_istream() {
return is;
}
void set_istream(std::istream & stream) {
is = stream;
}
private:
std::istream& is;
}
First this code doesn't compile for some reason. Second it feels awkward that you have to call set_istream()
before it is usable. Is there a better way to get this done? Thanks.
EDIT: Apparently, trying to assign a reference is my silly doing, as many of you pointed out. The second part is how to pass in stream
information into singleton - it seems not worth it, which suggests this might be a wrong case for using it. thanks you all for your answers.