我正在尝试使用 std::shared_ptr
和 std::weak_ptr
来操纵对象。场景如下:
我有一个类 channel
的对象,它派生自一个抽象类 abstract::channel
(带有纯虚函数)。我有一个容器 channelContainer
(std::vector
),其中包含指向 channel
对象的共享指针 (std::shared_ptr
)。
现在,我有一个 deque (std::deque)
,其中包含对于 channelContainer
中每个对象的弱指针 (std::weak_ptr)
。让我们把这个 deque 命名为 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'
}
我特别关注“如何将引用转换为弱指针?”
weak_ptr
,因为它所引用的对象必须由shared_ptr
拥有。因此,您需要一个shared_ptr
或weak_ptr
来进行构造。 - Piotr99