Bober02
Bober02

Reputation: 15341

C++ - returning vector from function

Coming from a Java background, I am trying to understand pointers/references in C++. I am trying to return a vector from a function. Writing:

vector<char*> f(){
    vector<char*> vec;
    return vec;
}

would return the copy of the vector, correct? A better way would be to return a pointer to vector like this:

vector<char*>* f(){
    vector<char*>* vec = new vector<char*>;
    return vec;
}

Am I correct, or is this totally wrong?

Upvotes: 2

Views: 2461

Answers (3)

pmr
pmr

Reputation: 59811

In C++03 the returning by value most likely leads to RVO (Return Value Optimization) which will elide the unnecessary copy. In C++11 move semantics will take care of the copy.

So, why return by value in the first place? Because it prevents unnecessary objects with dynamic lifetimes. Your example code also doesn't respect any allocation policy a user of your function might want to use.

In general, returning a container is even in C++11 still a bad idea: It restricts users to that specific container as it is not possible to move across containers, only to copy. The standard library solves this problem with OutputIteratorS. Your algorithm would most likely be written as:

template<typename OutputIterator>
OutputIterator f(OutputIterator o);

This way you abstract away from the container and also circumvent the original problem.

Upvotes: 1

Andy Prowl
Andy Prowl

Reputation: 126412

Am I correct, or is this totally wrong?

This is totally wrong, at least in C++11 where move semantics exists, and as long as you do not need to create aliases of the value you return (which does not seem to be your case and, even if it were, would likely require the use of smart pointers rather than raw pointers).

Returning a vector by value is OK now. Most of the time, even in C++98, the compiler would elide the call to the copy constructor anyway (and to the move constructor in C++11). This is called the (Named) Return Value Optimization.

In C++11, all the containers of the Standard Library support move constructors, so even when a copy or move is not elided, returning a container by value is not expensive.

Upvotes: 0

Yuushi
Yuushi

Reputation: 26040

You're wrong, you do not want to do this in C++. Pretty much every C++ compiler out there has what's called Named Return Value Optimization, which will (effectively) cause the vec to be moved, not copied, by allocating space for the return value on the stack, which is then basically constructed "in place". This eliminates the overhead.

The Wikipedia article on this gives a reasonable rundown.

Upvotes: 0

Related Questions