<p>In C++, what alternatives do I have for exposing a collection, from the point of view of performance and data integrity?</p>

<p>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.  </p>

<ul>
<li>Do I have to choose between performance and data integrity?  </li>
<li>If so, is in general better to go one way or is it particular to the case?  </li>
<li>Are there other alternatives?</li>
</ul>

[{'answer_id': 44697, 'author': 'Ben Collins', 'author_id': 3279, 'author_profile': 'https://Stackoverflow.com/users/3279', 'pm_score': 2, 'selected': False, 'text': "<p>Maybe something like this?</p>\n\n<pre><code>const std::vector&lt;mydata&gt;&amp; getData()\n{\n  return _myPrivateData;\n}\n</code></pre>\n\n<p>The benefit here is that it's very, very simple, and as safe as you getin C++.  You can cast this, like RobQ suggests, but there's nothing you can do that would prevent someone from that if you're not copying.  Here, you would have to use <code>const_cast</code>, which is pretty easy to spot if you're looking for it.</p>\n\n<p>Iterators, alternatively, might get you pretty much the same thing, but it's more complicated.  The only added benefit of using iterators here (that I can think of) is that you can have better encapsulation.</p>\n"}, {'answer_id': 44706, 'author': 'Henk', 'author_id': 4613, 'author_profile': 'https://Stackoverflow.com/users/4613', 'pm_score': 0, 'selected': False, 'text': '<p>Using const is a reasonable choice.\nYou may also wish to check out the boost C++ library for their shared pointer implementation. It provides the advantages of pointers i.e. you may have the requirement to return a shared pointer to "null" which a reference would not allow.</p>\n\n<p><a href="http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/smart_ptr.htm" rel="nofollow noreferrer">http://www.boost.org/doc/libs/1_36_0/libs/smart_ptr/smart_ptr.htm</a></p>\n\n<p>In your case you would make the shared pointer\'s type const to prohibit writes.</p>\n'}, {'answer_id': 44762, 'author': 'Shog9', 'author_id': 811, 'author_profile': 'https://Stackoverflow.com/users/811', 'pm_score': 4, 'selected': True, 'text': '<p><a href="https://stackoverflow.com/questions/44693/in-c-what-alternatives-do-i-have-for-exposing-a-collection-from-the-point-of-vi#44734">RichQ\'s answer</a> is a reasonable technique, if you\'re using an array, vector, etc. </p>\n\n<p>If you\'re using a collection that isn\'t indexed by ordinal values... or think you <em>might need to</em> at some point in the near future... then you might want to consider exposing your own iterator type(s), and associated <code>begin()</code>/<code>end()</code> methods:</p>\n\n<pre><code>class Blah\n{\npublic:\n   typedef std::vector&lt;mydata&gt; mydata_collection;\n   typedef myDataCollection::const_iterator mydata_const_iterator;\n\n   // ...\n\n   mydata_const_iterator data_begin() const \n      { return myPreciousData.begin(); }\n   mydata_const_iterator data_end() const \n      { return myPreciousData.end(); }\n\nprivate:\n   mydata_collection  myPreciousData;\n};\n</code></pre>\n\n<p>...which you can then use in the normal fashion:</p>\n\n<pre><code>Blah blah;\nfor (Blah::mydata_const_iterator itr = blah.data_begin();\n   itr != blah.data_end();\n   ++itr)\n{\n   // ...\n}\n</code></pre>\n'}, {'answer_id': 44785, 'author': 'Orion Edwards', 'author_id': 234, 'author_profile': 'https://Stackoverflow.com/users/234', 'pm_score': 0, 'selected': False, 'text': "<p>If you have a <code>std::list</code> of plain old data (what .NET would call 'value types'), then returning a const reference to that list will be fine (ignoring evil things like <code>const_cast</code>)</p>\n\n<p>If you have a <code>std::list</code> of pointers (or <code>boost::shared_ptr</code>'s) then that will only stop you modifying the collection, not the items <em>in</em> the collection. My C++ is too rusty to be able to tell you the answer to that at this point :-(</p>\n"}, {'answer_id': 44790, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>Use of const reference or shared pointer will only help if the contents of underlying collection do not change over time.</p>\n\n<p>Consider your design. Does the caller really need to see the internal array? Can you restructure the code so that the caller tells object what to do with the array? E.g., if the caller intends to search the array, could the owner object do it?</p>\n\n<p>You could pass a reference to result vector to the function. On some compilers that may result in marginally faster code.</p>\n\n<p>I would recommend trying to redesign first, going with a clean solution second, optimizing for performance third (if necessary).  </p>\n'}, {'answer_id': 44797, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>What you want is read-only access without copying the entire blob of data. You have a couple options.</p>\n\n<p>Firstly, you could just return a const refererence to whatever your data container is, like suggested above:</p>\n\n<pre><code>const std::vector&lt;T&gt;&amp; getData() { return mData; }\n</code></pre>\n\n<p>This has the disadvantage of concreteness: you can\'t change how you store the data internally without changing the interface of your class.</p>\n\n<p>Secondly, you can return const-ed pointers to the actual data:</p>\n\n<pre><code>const T* getDataAt(size_t index)\n{\n   return &amp;mData[index];\n}\n</code></pre>\n\n<p>This is a bit nicer, but also requires that you provide a getNumItems call, and protect against out-of-bounds indices. Also, the const-ness of your pointers is easily cast away, and your data is now read-write.</p>\n\n<p>Another option is to provide a pair of iterators, which is a bit more complex. This has the same advantages of pointers, as well as not (necessarily) needing to provide a getNumItems call, and there\'s considerably more work involved to strip the iterators of their const-ness.</p>\n\n<p>Probably the easiest way to manage this is by using a Boost Range:</p>\n\n<pre><code>typedef vector&lt;T&gt;::const_iterator range_iterator_type;\nboost::iterator_range&lt; range_iterator_type &gt;&amp; getDataRange()\n{\n    return boost::iterator_range(mData.begin(), mData.end());\n}\n</code></pre>\n\n<p>This has the advantages of ranges being composable, filterable, etc, as you can see on the <a href="http://www.boost.org/doc/libs/1_36_0/libs/range/index.html" rel="nofollow noreferrer">website</a>.</p>\n'}, {'answer_id': 44798, 'author': 'JohnMcG', 'author_id': 1674, 'author_profile': 'https://Stackoverflow.com/users/1674', 'pm_score': 2, 'selected': False, 'text': "<p>One advantage of both @Shog9's  and @RichQ's solutions is that they de-couple the client from the collection implementation.</p>\n\n<p>If you decide th change your collection type to something else, your clients will still work.</p>\n"}, {'answer_id': 45064, 'author': 'David Joyner', 'author_id': 1146, 'author_profile': 'https://Stackoverflow.com/users/1146', 'pm_score': 3, 'selected': False, 'text': "<p>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.</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;boost/function.hpp&gt;\n\nclass Blah\n{\n  public:\n     void for_each_data(const std::function&lt;void(const mydata&amp;)&gt;&amp; f) const\n     {\n         std::for_each(myPreciousData.begin(), myPreciousData.end(), f);\n     }\n\n  private:\n     typedef std::vector&lt;mydata&gt; mydata_collection;\n     mydata_collection  myPreciousData;\n};\n</code></pre>\n\n<p>With this approach you're not exposing anything about your internals, i.e. that you even <em>have</em> a collection.</p>\n"}, {'answer_id': 964164, 'author': 'Skeve', 'author_id': 33104, 'author_profile': 'https://Stackoverflow.com/users/33104', 'pm_score': 0, 'selected': False, 'text': '<p>The following two articles elaborate on some of the issues involved in, and the need for, encapsulating container classes. Although they do not provide a complete worked solution, they essentially lead to the same approach as given by Shog9.</p>\n\n<p>Part 1: <a href="http://stareast.techwelldev.com/sites/default/files/articles/Encapsulation_and_Vampires.pdf" rel="nofollow noreferrer">Encapsulation and Vampires</a> <br>\nPart 2 (free registration is now required to read this): <a href="https://www.stickyminds.com/better-software-magazine/train-wreck-spotting" rel="nofollow noreferrer">Train Wreck Spotting</a><br>\n by Kevlin Henney</p>\n'}, {'answer_id': 968346, 'author': 'Agnel Kurian', 'author_id': 45603, 'author_profile': 'https://Stackoverflow.com/users/45603', 'pm_score': 0, 'selected': False, 'text': '<p>I suggest using callbacks along the lines of <a href="http://msdn.microsoft.com/en-us/library/ms633494(VS.85).aspx" rel="nofollow noreferrer">EnumChildWindows</a>. You will have to find some means to prevent the user from changing your data. Maybe use a <code>const</code> pointer/reference.</p>\n\n<p>On the other hand, you could pass a copy of each element to the callback function overwriting the copy each time. (You do not want to generate a copy of your entire collection. I am only suggesting making a copy one element at a time. That shouldn\'t take much time/memory).</p>\n\n<pre><code>MyClass tmp;\nfor(int i = 0; i &lt; n; i++){\n    tmp = elements[i];\n    callback(tmp);\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/44693', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3081/']