c++ - use of boost::ref for passing reference to functions that take values -
i confused use of boost::ref. dont understand why 1 want 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 use of passing ref function. can pass value instead. not ref passed. in above value of aaa in main remains 2 only.
where boost ref useful?
is possible use boost::ref in scenario. want pass iterator refernce std::sort function. sort works on iterator copies - boost::ref make work references also? (without changes std::sort)
i dont understand why 1 want following
they wouldn't. that's not boost::ref
(or these days std::ref
) for. if function takes argument value, there's no way force take reference instead.
where boost ref useful?
it can used make function template act if takes argument reference, instantiating template reference (wrapper) type, rather value type:
template <typename t> void f(t x) {++x;} f(aaa); cout << aaa << endl; // increments copy: prints 0 f(ref(aaa)); cout << aaa << endl; // increments "a" itself: prints 1
a common specific use binding arguments functions:
void f(int & x) {++x;} int aaa = 0; auto byval = bind(f, aaa); // binds copy auto byref = bind(f, ref(aaa)); // binds reference byval(); cout << aaa << endl; // increments copy: prints 0 byref(); cout << aaa << endl; // increments "a" itself: prints 1
is possible use boost:;ref in scenario. want pass iterator refernce std::sort function. sort works on iterator copies - boost::ref make work references also?
no; reference wrapper doesn't meet iterator requirements, can't use in standard algorithms. if could, many algorithms go horribly wrong if needed make independent copies of iterators (as many, including sort
implementations, must do).
Comments
Post a Comment