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>& 开发者_StackOverflownewModel)
{
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?
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.
I guess you want to do something like this:
boost::shared_ptr<Asset::Model> ptr;
if(Load("stuff", ptr))
{
doSomething with ptr
}
In this case you should be fine.
However you don't need to use a reference here. Just return a shared_ptr
and set it to 0 if no element was found:
boost::shared_ptr<Asset::Model> Load(std::string name)
{
std::map<std::string, boost::scoped_ptr<Asset::Model> >::const_iterator seeker;
boost::shared_ptr<Asset::Model> retPtr;
seeker = models.find(name);
if (seeker == models.end())
return retPtr;
retPtr = seeker->second->Copy(); // Copy returns a boost::shared_ptr<Asset::Model>
return retPtr;
}
However I noticed you are using scoped_ptr
in a standard container - which AFAIK is not possible.
精彩评论