boost :: ref和常规引用之间的区别

Ven*_*iva 9 c++ boost reference

boost::ref(i)和之间有什么区别& i?在哪些情况下我们不能使用常规参考而必须boost::ref改为使用?如果可能,请提供示例.

pmr*_*pmr 7

来自Boost.Ref文档:

boost :: reference_wrapper的目的是包含对类型为T的对象的引用.它主要用于"提供"对按值引用其参数的函数模板(算法)的引用.

注意:boost::reference_wrapperstd::reference_wrapper(至少Boost 1.52)之间的一个重要区别是std::reference_wrapper完美地包装函数对象的能力.

这样可以实现如下代码:

// functor that counts how often it was applied
struct counting_plus {
  counting_plus() : applications(0) {}
  int applications;

  int operator()(const int& x, const int& y) 
  { ++applications; return x + y; }
};

std::vector<int> x = {1, 2, 3}, y = {1, 2, 3}, result;
counting_plus f;
std::transform(begin(x), end(x), begin(y), 
               std::back_inserter(result), std::ref(f));
std::cout << "counting_plus has been applied " << f.applications 
          << " times." << '\n';
Run Code Online (Sandbox Code Playgroud)