Avoiding temporary variables when returning vectors from two or more functions

273 Views Asked by At

I wonder if there is any way to avoid extra copies when returning std::vector's by a function and "creating" their values directly in vector "integers". The most usual way of doing so before c++11 was passing main std::vector by reference (&) and use it within the filling functions, but I would like to avoid that approach and try something more modern c++ way.

#include <vector>

std::vector<int> function1()
{
    std::vector<int> v;
    v.emplace_back(1);
    v.emplace_back(2);
    v.emplace_back(3);
    
    return v;
}

std::vector<int> function2()
{
    std::vector<int> v;
    v.emplace_back(10);
    v.emplace_back(11);
    
    return v;
}

int main()
{
    std::vector<int> integers;
    
    const auto v1 = function1();
    std::copy(v1.begin(), v1.end(), std::back_inserter(integers));
    
    const auto v2 = function2();
    std::copy(v2.begin(), v2.end(), std::back_inserter(integers));
    
    return 0;
}

What I want is to create directly the elements in the vector defined in main, if possible using c++11 or above features.

Thanks in advance.

1

There are 1 best solutions below

3
On

If you write your functions like this:

std::vector<int> function1()
{
    return std::vector<int> {1, 2, 3};
}

std::vector<int> function2()
{
    return std::vector<int> {10, 11};
}

then from c++17, RVO is mandatory, and the vectors will be constructed directly at the call site.


From c++20, you can avoid creating the vector in main at all, by doing:

std::ranges::copy(function1(), std::back_inserter(integers));
std::ranges::copy(function2(), std::back_inserter(integers));