c++ - Interface for returning a bunch of values -


i have function takes number , returns many things (say, ints). what's cleanest interface? thoughts:

  1. return vector<int>. vector copied several times, inefficient.
  2. 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.
  3. return unique_ptr<vector<int>>. it's clear deletes it, still have other problems.
  4. take vector<int> reference parameter. getter can push_back() , caller can decide whether reserve() space. however, should getter if passed-in vector non-empty? append? overwrite clearing first? assert it's empty? nice if signature of function allowed single interpretation.
  5. pass begin , end iterator. need return number of items written (which might smaller desired), , caller needs careful not access items never written to.
  6. have getter take iterator, , caller can pass insert_iterator.
  7. 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

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -