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
Is this your design? As is, there are some serious channel lifetime issues. For example - if code calls get_free_channel()
then your declaration returns them a reference to an object, but they have no way to guarantee it's lifetime encompasses their use. That might not matter depending on what the client code is that you're calling the function from, but you probably want to return a shared_ptr
, as in:
std::shared_ptr get_free_channel()
{
// return free channel from 'freeChannelQueue' and pop the queue
// take a scoped lock on the free queue if necessary
while (!freeChannelQueue.empty())
{
auto p_channel = freeChannelQueue.back();
freeChannelQueue.pop_back();
std::shared_ptr p = p_channel.lock();
if (p) return p;
}
// freeChannelQueue empty... throw or return nullptr etc..
}
Regarding "release"...
bool release_channel(abstract::channel& ch) {
//This should convert 'ch' to a std::weak_ptr (or std::shared_ptr) and push it to 'freeChannelQueue'
}
As is, this is only possible if you search the channelContainer
to find the object then get your weak_ptr or shared_ptr from there. Again - you should probably change the prototype so it receives a shared_ptr
or weak_ptr
directly, locks the free queue then pushes the smart pointer on....
All in all, it's hard to give you useful advice without understanding the way your channel lifetime is going to be managed, and how various threads might attempt to use the objects and queues. I hope the above helps a little, even if only in asking a more precise question.