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
makemake_tuple(0,ref(a))
tuple
- 你也可以说
元组t(0,a)对于不能使用
或使用make\u tuple
生成的元组,code>std::tie
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
toT&
。它们是可以识别的,因为它们通常是按照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;
}