c++ - Interface for returning a bunch of values -
i have function takes number , returns many things (say, ints). what's cleanest interface? thoughts:
- return
vector<int>
. vector copied several times, inefficient. - return
vector<int>*
. getter has allocate vector itself, elements. there usual problems of has free vector, fact can't allocate once , use same storage many different calls getter, etc. why stl algorithms typically avoid allocating memory, instead wanting passed in. - return
unique_ptr<vector<int>>
. it's clear deletes it, still have other problems. - take
vector<int>
reference parameter. getter canpush_back()
, caller can decide whetherreserve()
space. however, should getter if passed-invector
non-empty? append? overwrite clearing first? assert it's empty? nice if signature of function allowed single interpretation. - pass
begin
,end
iterator. need return number of items written (which might smaller desired), , caller needs careful not access items never written to. - have getter take
iterator
, , caller can passinsert_iterator
. - give , pass
char *
. :)
in c++11, move semantics supported standard containers, you should go option 1.
it makes signature of function clear, communicating want vector of integers returned, , efficient, because no copy issued: move constructor of std::vector
invoked (or, likely, named return value optimization applied, resulting in no move , no copy):
std::vector<int> foo() { std::vector<int> v; // fill in v... return v; }
this way won't have deal issues such ownership, unnecessary dynamic allocations, , other stuff polluting simplicity of problem: returning bunch of integers.
in c++03, may want go option 4 , take lvalue reference non-const
vector: standard containers in c++03 not move-aware, , copying vector may expensive. thus:
void foo(std::vector<int>& v) { // fill in v... }
however, in case, should consider whether penalty significant use cases. if not, may opt clearer function signature @ expense of cpu cycles.
also, c++03 compilers capable of performing named return value optimization, though in theory temporary should copy-constructed value return, in practice no copying happen.
Comments
Post a Comment