Search code examples
c++boostresourcemanager

safety of passing boost::shared_ptr reference


my question is, how fail-safe is the following code snippet which is part of my resource manager:

 bool Load(std::string name, boost::shared_ptr<Asset::Model>& newModel)
 {
  std::map<std::string, boost::scoped_ptr<Asset::Model> >::const_iterator seeker;

  seeker = models.find(name);
  if (seeker == models.end())
   return false;

  newModel = seeker->second->Copy(); // Copy returns a boost::shared_ptr<Asset::Model>
  return true;
 }

private:
 std::map< std::string, boost::scoped_ptr<Asset::Model> >  models;

because passing boost's shared_ptr by reference is actually not part of the shared_ptr concept, if i only use it in this scope, could i run into trouble?


Solution

  • This usage is safe, in that whatever the shared_ptr<> passed in through the reference will have it's refcount reduced (assuming that the shared_ptr<> returned from seeker->second->Copy() isn't a shared_ptr<> to the same object) and therefore the object it will be pointing to might be deleted.

    Specifically, you aren't creating a second shared_ptr<> from a raw pointer (which is an error because it would create a second, unrelated shared_ptr<> with a separate refcount, and therefore a second owner of the object).

    Whether your function provides the behavior you want depends on what you want.