user1486293
user1486293

Reputation: 79

Passing vector by reference in boost::bind

Why is the output of this 0?

http://ideone.com/S7hgv

#include <boost/bind.hpp>
#include <vector>
#include <iostream>

using namespace std;

void f2(vector<int> &h)
{
        h.clear();
        h.push_back(0);
}

void f1(vector<int> &h)
{
        boost::bind(f2, boost::ref(h));
}

int main()
{
        vector<int> h;
        f1(h);

        cout << h.size() << "\n";
}

I need it to be 1, and for some reason h is not modified.

Upvotes: 0

Views: 640

Answers (1)

Cubbi
Cubbi

Reputation: 47428

boost/std::bind() only constructs the function object. You still have to call it, in order for any code inside to execute.

To get the output of 1, replace the line

    boost::bind(f2, boost::ref(h));

with

    boost::bind(f2, boost::ref(h))();

Upvotes: 4

Related Questions