Search code examples
performancec++11vectorstlbind

std::bind - vector as an argument in bound function


I have a question which way is the best to forward vector to bound function?

Below is code with two approaches. In production code vector will contain huge amount of data and I would like to avoid copying it as much as possible.

#include <iostream>
#include <vector>
#include <functional>

void foo(const std::vector<uint16_t>& v)
{
    for(const auto& c : v)
    {
        std::cout << c;
    }

    std::cout << std::endl;
}

int main()
{
    std::vector<uint16_t> vv{1, 2, 3, 4, 5, 6, 7, 8, 9, 0};

    auto f1 = std::bind(&foo, vv); // 1)
    auto f2 = std::bind(&foo, std::move(vv)); // 2)

    f1();
    f2();
}

Solution

  • It really depends on what you want to do with the bound functions.

    If they are going to be copied passed around (beyond the life of vv), this is correct (and is going to copy vv).

    auto f1 = std::bind(&foo, vv); // 1)
    

    This is also correct, (vv is not going to be copied initially at least.)

    auto f2 = std::bind(&foo, std::move(vv)); // 2)
    

    but you will not have access to vv after that point.

    This is however the most likely scenario that I can deduce from your example: if the bound function will be used locally while vv is still alive it is more likely from the example that want you want f3 to hold a "reference" to vv. This is done with the ref convention:

    auto f3 = std::bind(&foo, std::ref(vv));