什么时候需要使用 std::ref ?

新手上路,请多包涵

考虑:

 std::tuple<int , const A&> func (const A& a)
{
  return std::make_tuple( 0 , std::ref(a) );
}

编写正确且可移植的代码是否需要 std::ref ? (没有它编译很好)

背景:

如果我删除 std::ref 我的代码构建良好,没有任何警告( g++-4.6 -Wall ),但运行不正确。

如果感兴趣,定义 A

 struct A {
  std::array<int,2> vec;
  typedef int type_t;

  template<typename... OPs,typename... VALs>
  A& operator=(const std::pair< std::tuple<VALs...> , std::tuple<OPs...> >& e) {
    for( int i = 0 ; i < vec.size() ; ++i ) {
      vec[i] = eval( extract(i,e.first) , e.second );
    }
  }
};

原文由 ritter 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 661
2 个回答
  • make_tuple(0, a) 制作一个 tuple<int, A>
  • make_tuple(0, ref(a)) 制作一个 tuple<int, reference_wrapper<A>>
  • 你也可以说 tuple<int, A&> t(0, a); 对于你不能用 make_tuple 制作的元组,或者使用 std::tie

原文由 Kerrek SB 发布,翻译遵循 CC BY-SA 3.0 许可协议

需要 std::ref 的示例之一:

 void update(int &data)  //expects a reference to int
{
    data = 15;
}
int main()
{
    int data = 10;

    // This doesn't compile as the data value is copied when its reference is expected.
    //std::thread t1(update, data);

    std::thread t1(update, std::ref(data));  // works

    t1.join();
    return 0;
}

std::thread 构造函数复制提供的值,而不转换为预期的参数类型(在这种情况下是 引用 类型,请参见 update() )。所以我们需要 将真正需要引用的参数包装std::ref 中。

原文由 Saurav Sahu 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题