1

How should I properly return a vector from a function to a void extra copying?

If I return just vector then I should create a vector in the function and then on return it will be copied in the result. But I want to avoid that. Then I guess I should create the vector on the heap and return a pointer to it vector* ?

Thanks

Elazar
  • 20,415
  • 4
  • 46
  • 67
user2381422
  • 5,645
  • 14
  • 42
  • 56
  • You can look into references, http://stackoverflow.com/questions/752658/is-the-practice-of-returning-a-c-reference-variable-evil – Djon Jun 03 '13 at 07:51
  • 3
    http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/ – hmjd Jun 03 '13 at 07:51
  • 3
    Just return it by value, unless you are completely sure that your compiler does not elide the copy and you don't have C++11 move semantics. – juanchopanza Jun 03 '13 at 07:53
  • There is also 1) http://stackoverflow.com/questions/4809120/creating-and-returning-a-big-object-from-a-function and 2) http://stackoverflow.com/questions/3134831/in-c-is-it-still-bad-practice-to-return-a-vector-from-a-function The latter is of particular interest if you can use C++11. – jogojapan Jun 03 '13 at 07:55

2 Answers2

2

The C++ Standard allows your compiler to eliminate this copy in certain cirumstances (Section 12.8.5). It's difficult to tell whether your compiler actually does this, so you should read its documentation or look at generated assembler code. So it's probably better to let your compiler do optimisations for you.

But if you really like optimising by hands (you shouldn't), read on.

Allocating vector on heap and returning a pointer to it is a bad thing to do, because in this case it is not clear who's responsible for this object and who'll do memory cleanup.

Making your function take an additional argument—reference or pointer to a vector to store result into—is way better.

kirelagin
  • 13,248
  • 2
  • 42
  • 57
1

I would pass a reference to it as a parameter.

void foo(std::vector& bas)
{
// do code here
}
graham.reeds
  • 16,230
  • 17
  • 74
  • 137