rit*_*ter 24 c++ portability correctness c++11
考虑:
std::tuple<int , const A&> func (const A& a)
{
return std::make_tuple( 0 , std::ref(a) );
}
Run Code Online (Sandbox Code Playgroud)
是否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 );
}
}
};
Run Code Online (Sandbox Code Playgroud)
Ker*_* SB 15
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
.jua*_*nza 12
std::ref
没有引用,所以在你的代码示例中它没有做你期望的.std::ref
创建一个与引用类似的对象.例如,当您想要实例化仿函数并将其类似引用的版本传递给标准库算法时,它可能很有用.由于算法按值使用仿函数,因此您可以使用std::ref
包装仿函数.
Sau*_*ahu 10
其中一个例子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;
}
Run Code Online (Sandbox Code Playgroud)
该std::thread
构造拷贝所提供的值,而不转换为预期的参数类型(其是参考类型在这种情况下,看到update()
).因此,我们需要换行真正需要引用的论据在std::ref
.
归档时间: |
|
查看次数: |
8246 次 |
最近记录: |