I am trying to refactor some oldish code, and I want to use unique_ptrs for some objects where they are clearly suited. Up till now, shared_ptrs have been generally used.
Given that for most intents and purposes both smart pointers behave identically, in many cases I don't see why I should have to distinguish between the two. So to make a trivial example:
EDIT: I've had to make the object a little less trivial...
class NamedItem
{
string name;
string& GetName();
}
class SessionObject: public NamedItem
{}
class TrivialObject: public NamedItem
{}
class NameCacher:
{
vector<??????<NamedItem>> named_items;
void AddNamedItem(??????<NamedItem>& named_item)
{
named_items.push_back(named_item);
}
void PrintAllNamedItems()
{
// Print all names
}
}
unique_ptr<SessionObject> session(new SessionObject("the session"));
shared_ptr<TrivialObject> some_object(new TrivialObject("whatever"));
NameCacher names();
names.AddNamedItem(session); // The session pointer will not delete the session object, even if names stops referencing it.
names.AddNamedItem(some_object); // The some_object pointer is welcome to delete itself if names stops referencing it and nothing else is.
names.PrintAllNamedItems();
// If some_object goes out of scope, then its shared_ptr will delete it at this point.
Given that 80% of the day-to-day behaviour of the smart pointers is the same, isn't there a way to do this? The only thing I've found is to convert a unique_ptr to a shared_ptr - which is categorically not what I want to do. Ideally, I'd like the base class of the two smart pointers - but I can't find one.