繁体   English   中英

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

[英]Difference between boost::ref and regular references

boost::ref(i)& i什么区别? 有什么情况我们不能使用常规引用而必须转而使用boost::ref 如果可能,请提供示例。

来自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';

Boost.Thread为例:

通过将可调用的可调用类型的对象传递给构造函数来启动新线程。 然后将该对象复制到内部存储中,并在新创建的执行线程上调用。 如果不能(或不能)复制对象,则可以使用boost :: ref传入对函数对象的引用。 在这种情况下,Boost.Thread的用户必须确保引用的对象超过新创建的执行线程。

来自doc的代码:

struct callable
{
    void operator()();
};

boost::thread copies_are_safe()
{
    callable x;
    return boost::thread(x);
} // x is destroyed, but the newly-created thread has a copy, so this is OK

boost::thread oops()
{
    callable x;
    return boost::thread(boost::ref(x));
} // x is destroyed, but the newly-created thread still has a reference
  // this leads to undefined behaviour

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM