I am trying to juggle objects using std::shared_ptr
and std::weak_ptr
. The scenario is something like this:
I have objects of class chann
I understand your question like this: you have a container to hold all of your channel objects and you have a second container to maintain an order of which channels can be used by your application. You would then like an interface to return a reference to the next free channel for your client, and when the client is finished it releases the channel back to the container.
To get a reference to a channel you can use lock to create a shared_ptr from your weak_ptr and then dereference that (just don't delete the underlying object!). However, I don't see a sensible way to go the other way, you would need to search your channel container for the object that matches and create a weak pointer from the matching shared_ptr again.
I would consider not using weak_ptr and references at all, just stick with shared_ptr. Since you use a deque to maintain which channels are available, you could instead just keep the available shared_ptr's there. If you are happy that your client will always release the channels when finished, you perhaps don't need a container for all the objects, only the deque for the free channels - depends on your overall design.
As others have said, you need to consider the lifetime of your channel objects and how they are used by the client.