Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient alternatives for exposing a Collection

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?
like image 789
axs6791 Avatar asked Sep 04 '08 20:09

axs6791


1 Answers

Many times the caller wants access just to iterate over the collection. Take a page out of Ruby's book and make the iteration a private aspect of your class.

#include <algorithm>
#include <boost/function.hpp>

class Blah
{
  public:
     void for_each_data(const std::function<void(const mydata&)>& f) const
     {
         std::for_each(myPreciousData.begin(), myPreciousData.end(), f);
     }

  private:
     typedef std::vector<mydata> mydata_collection;
     mydata_collection  myPreciousData;
};

With this approach you're not exposing anything about your internals, i.e. that you even have a collection.

like image 73
David Joyner Avatar answered Sep 23 '22 00:09

David Joyner