After changing my code to use unique pointers, I stumbled upon how to return a collection of objects to a client. In general, I want to pass objects as references or non-owning pointers. But if I have a collection of objects, I can't just return the reference to it.
As an example, I have a simple class with a collection of objects, which are all created once and not altered afterwards.
using ObjectUPtr = std::unique_ptr<Object>;
class MyClass
{
public:
const std::vector<Object*>& GetObjectsOldStyle() const
{
return mObjectsOldStyle;
}
const std::vector<VObjectUPtr>& GetObjectsNewStyleA() const
{
// I don't like that: The client should not see the unique_ptr ...
return mObjectsNewStyle;
}
std::vector<VObject*> GetObjectsNewStyleB() const
{
// Ok, but performance drops
std::transform(...); // Transform the collection and return a copy
}
const std::vector<VObject*>& GetObjectsNewStyleC() const
{
// Ok, only copied once, but two variables per collection needed
// Transform the collection and cache in a second vector<Object*>
std::transform(...);
}
std::vector<Object*> mObjectsOldStyle; // old-style owning pointers here
std::vector<ObjectUPtr> mObjectsNewStyle; // how I want to do it today
}
Today, I usually prefer GetObjectsNewStyleB, but I wonder, if there is a more elegant and efficient way or a general best practice on how to return such collections.
Aucun commentaire:
Enregistrer un commentaire