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?
- Return a
vector<int>
. The vector would be copied several times, which is inefficient.- 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.- Return a
unique_ptr<vector<int>>
. It's now clear who deletes it, but we still have the other problems.- Take a
vector<int>
as a reference parameter. The getter canpush_back()
and the caller can decide whether toreserve()
the space. However, what should the getter do if the passed-invector
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.- 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.
- Have the getter take an iterator, and the caller can pass an
insert_iterator
.- Give up and just pass a
char *
.
Add a Comment
Comments are closed.