shared_ptr & weak_ptr conversions

user2559933 picture user2559933 · Jul 8, 2013 · Viewed 30.3k times · Source

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 channel which is derived from a abstract class abstract::channel (with pure virtual functions). I have a container channelContainer (std::vector) containing shared pointers (std::shared_ptr) to channel Objects.

Now, I have a deque (std::deque) containing weak pointers (std::weak_ptr) to each of the object in the channelContainer. Lets name this deque freeChannelQueue.

So lets say:

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'
}

I am particularly interested in the 'How to convert a reference to an object to a weak pointer?'

Answer

doctorlove picture doctorlove · Jul 8, 2013

You cannot

convert a reference to an object to a weak pointer

You can make a weak pointer from a shared pointer, just using assignment = e.g.

std::shared_ptr<abstract::channel> get_free_channel();

then

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

Watch out for lifetimes - will the shared_ptr go before the weak pointers that point to them?