shared_ptr和weak_ptr转换

use*_*933 15 c++ pointers shared

我正在尝试使用std::shared_ptr和处理对象std::weak_ptr.场景是这样的:

我有一个类的对象,channel它派生自一个抽象类abstract::channel(使用纯虚函数).我有一个容器channelContainer(std::vector)包含对象的共享指针(std::shared_ptr)channel.

现在,我有一个deque (std::deque)包含弱指针(std::weak_ptr)的每个对象channelContainer.让我们说出这个双端队列freeChannelQueue.

所以我们说:

std::vector<std::shared_ptr<abstract::channel> > channelContainer;
std::deque<std::weak_ptr<abstract::channel > > freeChannelQueue;

//Assuming that both the containers are filled appropriately How do I go about implementeing the below functions?

abstract::channel& get_free_channel() {
  //This should return a free channel object from 'freeChannelQueue' and pop the queue.
}

bool release_channel(abstract::channel& ch) {
 //This should convert 'ch' to a std::weak_ptr (or std::shared_ptr) and push it to   'freeChannelQueue'
}
Run Code Online (Sandbox Code Playgroud)

我对'如何将对象的引用转换为弱指针?'特别感兴趣?

doc*_*ove 9

你不能

将对象的引用转换为弱指针

您可以从一个共享指针做一个弱指针,只是用分配=

std::shared_ptr<abstract::channel> get_free_channel();
Run Code Online (Sandbox Code Playgroud)

然后

bool release_channel(std::shared_ptr<abstract::channel> ch)
{
    std::weak_ptr<abstract::channel> weak_ch = ch;
    //...
}
Run Code Online (Sandbox Code Playgroud)

注意一生 - shared_ptr会在指向它们的弱指针之前消失吗?


Ton*_*roy 1

这是你的设计吗?事实上,存在一些严重的通道寿命问题。例如 - 如果代码调用get_free_channel(),那么您的声明将返回对对象的引用,但它们无法保证其生命周期包含它们的使用。这可能并不重要,具体取决于您调用函数的客户端代码是什么,但您可能希望返回 a shared_ptr,如下所示:

std::shared_ptr<abstract::channel> 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<abstract::channel> p = p_channel.lock();
         if (p) return p;
    }

    // freeChannelQueue empty... throw or return nullptr etc..
}
Run Code Online (Sandbox Code Playgroud)

关于“释放”...

bool release_channel(abstract::channel& ch) {
 //This should convert 'ch' to a std::weak_ptr (or std::shared_ptr) and push it to   'freeChannelQueue'
}
Run Code Online (Sandbox Code Playgroud)

事实上,只有当您搜索channelContainer找到对象然后从那里获取weak_ptr或shared_ptr时,这才有可能。再次 - 您可能应该更改原型,以便它直接接收shared_ptrweak_ptr,锁定空闲队列,然后推送智能指针......

总而言之,如果不了解通道生命周期的管理方式以及各种线程如何尝试使用对象和队列,就很难为您提供有用的建议。我希望以上内容能有所帮助,即使只是提出更精确的问题。