I am confused about the use of boost::ref. I dont understand why any one would want to do the following -
void f(int x)
{
cout << x<<endl;
x++;
}
int main(int argc, char *argv[])
{
int aaa=2;
f(boost::ref(aaa));
cout << aaa<<endl;
exit(0);
}
What is the use of passing a ref to a function. I can always pass by value instead. Also it not that the ref is actually passed. In the above the value of aaa in main remains 2 only.
Where exactly is boost ref useful?
Is it possible to use boost::ref in this scenario. I want to pass iterator refernce to std::sort function. normally the sort works on iterator copies - will boost::ref make it work for references also? (without any changes to std::sort)
They wouldn't. That's not what
boost::ref
(or these daysstd::ref
) is for. If a function takes an argument by value, then there's no way to force it to take it by reference instead.It can be used to make a function template act as if it takes an argument by reference, by instantiating the template for the reference (wrapper) type, rather than the value type:
A common specific use is for binding arguments to functions:
No; the reference wrapper doesn't meet the iterator requirements, so you can't use it in standard algorithms. If you could, then many algorithms would go horribly wrong if they needed to make independent copies of iterators (as many, including most
sort
implementations, must do).