I have a situation where I have a piece of hardware and it really only makes sense for a single connection to be open on that hardware at the same time, so I really only want to refer to one object no matter where it's passed. So it may look something like:
class Hardware {
public:
void Open(); //this will create and launch a connection monitor in the background
void Close();
std::string SendPing();
std::string AskForSomeOtherData();
bool isConnected();
bool setConnected(bool connState);
private:
bool connected_;
int hndl_;
}
I then have another class monitoring the connection in the background so my UI can be notified if a connection is lost.
class ConnectionMonitor{
ConnectionMonitor(Hardware& hw);
void Run(); //launches a background thread to send "pings" to the device to make sure it's there. Will update Hardware.connected_
Hardware hw_; //or Hardware* hw_, or shared_ptr<Hardware> hw_, or Hardware& hw_;
}
When the connection monitor notices a connection is lost, it needs to update the connected boolean of the hardware object passed in directly, because my other threads using the object will also want to know it's been disconnected. But I don't know if updating the private data of the object indicates ownership of the object itself?
I don't believe so, since the lifetime of the object shouldn't be effected. There are all these different ways to pass an object shared between two classes, but I don't know what the problem domain calls for when I need to store it in class private data. Requiring a shared pointer to be passed in is one option. But I am not really indicating any ownership of the object being taken I don't think? A reference seems to be more fitting possibly, but then I end up with needing Hardware& hw;
in my ConnectionMonitor private data so I keep a reference to the Hardware object. Then I read stuff that says "Reference in private data bad."
Also, if the caller is storing the hardware object as a shared_ptr, I believe I would have to do something like the following to pass it into my ConnectionMonitor:
ConnectionMonitor(*hardware);
but is this ok for a shared pointer, to dereference it, pass the object to a constructor, and then have the consuming class store another pointer to the same object that the shared pointer owns?
ConnectionMonitor(Hardware& hw){
Hardware* = hw; //not 100% sure if this syntax is correct, still learning. Most importantly here I'd be taking the hw object being referenced and pointing at it internally, rather than creating a copy
}
It seems now I am now creating a pointer to an object that the shared pointer already owns.
There are a lot of questions embedded above in what amounts to be a brain dump on my thought process, so I will try to summarize. When two threads need access to the same resource, and that resource needs to be updated from either thread, is this a case for a shared pointer? If one of the classes is not taking ownership, what is the best way to store that shared object in private data?