I'm dealing specifically with C++, but this is really language-agnostic.
Just to give some context into the problem... I have a tree/graph based structure where each node holds a collection of multiple items.
I have a class which encapsulates some generic collection (list, map, vector, LinkedList, whatever). I want to be able to fetch all the items from that collection in the most efficient way possible without the client being able to edit the private collection.
Here is a simplified example of what I have:
class MyClass
{
public:
// Basic constructors and such
void AddItem(int item) { _myItems->push_back(item); }
private:
list<int>* _myItems;
};
So obviously a getter which retrieves the pointer to _myItems does not work as this will allow the client to edit _myItems.
Attempt 1:
I could create a new list and return a pointer to that one instead... however I don't like that idea as the responsibility of creating and deleting now lie with different objects.
Attempt 2:
I'm thinking it would be best to create some CopyTo methods such as:
void CopyItemsToList(list<int>* inList) { // copy the items to client list }
This way, the client takes care of mem management and it is easy to extend this to allow more data structures. My concern with this approach is cost... The list can be very big, and the cost of copying the items could get large
Attempt 3:
Instead of keeping a pointer to a list in the class, just use a value type and return that (letting the copy constructor take care of it). But, this seems like the performance cost will be the same as #2...
Anyways, any other way to go about this? Let me know what you guys think... Thanks.