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

4

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

And returning a value is way, way better.
@juanchopanza OK, I'll mention it…
I'm still missing any mentioning of move semantics in an answer with already 2 upvotes.
Note that, at elast with not too ancient versions of GCC, clang and MSVC, return value optimization is the norm, so you can be pretty confident it will take place (of course, if it matters, you can always check to be sure).
1

I would pass a reference to it as a parameter.

void foo(std::vector& bas)
{
// do code here
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.