1

So , I have done a fair bit of googling trying to figure out if there is some best smart pointer to handle this but I have not been able to settle on a good choice.

struct Car
{
    int m_doors;
    int m_headlights;
    //etc..
}

Lets say I have some class Car. I also have a std::map<int carkey, Car*> that is the JunkYard.

A Car* can be added to the JunkYard by some Driver, the Driver itself new'd the Car, but the driver immediately loses all responsibility of the Car*.

I would like the JunkYard to be responsible for all its cars, Cars in the JunkYard can be accessed by people to remove say parts and take scrap metal from the Car , or can be crushed but the JunkYard destroying it forever.

At the end of the day the JunkYard destroys all of its Cars and shuts down.

--

A) If this were a multithreaded app where Drivers could access cars concurrently while the JunkYard could destroy cars I was thinking that probably a shared_ptr would be best? Is this overkill though? Other threads may access the car but they will never take long term ownership of it, it must always remain belonging to the JunkYard.

B) If this were single threaded what would be the best choice -assuming its still a map< some_smart_car_ptr> . I want to have the container take car of deleting the Cars themselves. For example calling map.erase(...) should delete the pointer as well as removing it from the map.

skimon
  • 1,149
  • 2
  • 13
  • 26
  • What about `map`? If that doesn't work for some reason, I'd suggest `map>`. – Philipp Apr 01 '12 at 21:38
  • Thanks for this suggestion, using map and inserting into the map might cause reordering and thus copying and moving of Cars right? As far unique_ptr , is it possible to access unique_ptr by passing it as a ref ? I will look into this – skimon Apr 01 '12 at 21:50
  • unique_ptr is C++11 right? I don't have access to this. – skimon Apr 01 '12 at 21:57

1 Answers1

1

Smart pointers are definitely preferred. Look at boost::shared_ptr for a header-only solution that scales well (and is in TR1 & C++11 / C++0x).

boost::unordered_map<int carKey, boost::shared_ptr<Car *> > myCollection;

Then just instantiate a new shared_ptr whenever you ref the data to increment the reference count. That alone will prevent premature deletion. Ensure you lock the pointer acquisition & collection lookup within a scoped mutex. A method of such like:

boost::shared_ptr<Car *> CarManager::get(int carKey) {
    boost::mutex::scoped_lock lock(mutex);

    // ... etc ... //
}
pestilence669
  • 5,698
  • 1
  • 23
  • 35
  • Understood, but my question is - can I use something other than a shared_ptr. In this case nothing can ever delete a Car while the JunkYard owns it so can I use something more basic (no ref counting), but would still allow me to temporarily get the pointer for use? – skimon Apr 02 '12 at 03:36
  • see: http://www.boost.org/doc/libs/1_49_0/libs/ptr_container/doc/ptr_container.html – pestilence669 Jun 28 '12 at 00:00