C++ 何时需要使用std::ref?

C++ 何时需要使用std::ref?,c++,c++11,portability,correctness,C++,C++11,Portability,Correctness,考虑: std::tuple<int , const A&> func (const A& a) { return std::make_tuple( 0 , std::ref(a) ); } make_tuple(0,a)生成tuple make_tuple(0,ref(a))maketuple 你也可以说元组t(0,a) std::ref没有引用,因此在您的代码示例中,它没有实现您期望的功能std::ref创建行为类似于引用的对象。例如,当您想要实例化一个

考虑:

std::tuple<int , const A&> func (const A& a) 
{
  return std::make_tuple( 0 , std::ref(a) );
}
  • make_tuple(0,a)
    生成
    tuple
  • make_tuple(0,ref(a))
    make
    tuple
  • 你也可以说
    元组t(0,a)make\u tuple
    或使用
    std::tie
    生成的元组,code>

std::ref
没有引用,因此在您的代码示例中,它没有实现您期望的功能
std::ref
创建行为类似于引用的对象。例如,当您想要实例化一个函子,并将其类似引用的版本传递给标准库算法时,它可能很有用。由于算法按值获取函子,因此可以使用
std::ref
包装函子。

需要
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
中包装真正需要引用的参数

因此,如果
ref
被删除,它应该抛出一个错误。为什么不呢,有什么想法吗?@Frank:元组可以由任何人类可能的东西构造出来。您只需返回对局部变量的引用,即
a
的局部副本。使用
ref
返回对原始函数参数的包装引用。@弗兰克:换句话说,您应该说
return std::tuple(0,a)。我明白了。但是,正如您所说,将创建/返回一个
元组。如果将
tuple
作为返回类型,如何返回该值?严格来说
std::make_tuple(ref(a))
将导致
std::tuple
,而不是
std::tuple
。标准库中衰减其参数的许多部分的特殊情况是“衰减”
std::reference\u wrapper
to
T&
。它们是可以识别的,因为它们通常是按照
std::decay
来指定的,尽管
std::decay
本身并没有进行转换(有些令人沮丧)。在std::thread t1中也有很好的询问和回答(更新,数据);will编译得很好,但问题是它不会改变数据的值。
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;
}