In C++, what alternatives do I have for exposing a collection, from the point of view of performance and data integrity?
My problem is that I want to return an internal list of data to the caller, but I don’t want to generate a copy. Thant leaves me with either returning a reference to the list, or a pointer to the list. However, I’m not crazy about letting the caller change the data, I just want to let it read the data.
- Do I have to choose between performance and data integrity?
- If so, is in general better to go one way or is it particular to the case?
- Are there other alternatives?
RichQ’s answer is a reasonable technique, if you’re using an array, vector, etc.
If you’re using a collection that isn’t indexed by ordinal values… or think you might need to at some point in the near future… then you might want to consider exposing your own iterator type(s), and associated
begin()/end()methods:…which you can then use in the normal fashion: