shared_ptr & weak_ptr conversions

前端 未结 3 1330
攒了一身酷
攒了一身酷 2021-02-07 08:54

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

3条回答
  •  -上瘾入骨i
    2021-02-07 09:32

    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.

提交回复
热议问题