Quick Q: What's the best way to return multiple values? -- StackOverflow

Another example of how adding a feature, in this case move semantics, makes using the language simpler:

Interface for returning a bunch of values

I have a function that takes a number and returns up to that many things (say, ints). What's the cleanest interface?

  1. Return a vector<int>. The vector would be copied several times, which is inefficient.
  2. Return a vector<int>*. My getter now has to allocate the vector itself, as well as the elements. There are all the usual problems of who has to free the vector, the fact that you can't allocate once and use the same storage for many different calls to the getter, etc. This is why STL algorithms typically avoid allocating memory, instead wanting it passed in.
  3. Return a unique_ptr<vector<int>>. It's now clear who deletes it, but we still have the other problems.
  4. Take a vector<int> as a reference parameter. The getter can push_back() and the caller can decide whether to reserve() the space. However, what should the getter do if the passed-in vector is non-empty? Append? Overwrite by clearing it first? Assert that it's empty? It would be nice if the signature of the function allowed only a single interpretation.
  5. Pass a begin and end iterator. Now we need to return the number of items actually written (which might be smaller than desired), and the caller needs to be careful not to access items that were never written to.
  6. Have the getter take an iterator, and the caller can pass an insert_iterator.
  7. Give up and just pass a char *. smile

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.