简体   繁体   English

为什么std :: shuffle采用右值引用?

[英]Why does std::shuffle take an rvalue reference?

Since C++11 , std::shuffle() takes an rvalue reference to a random bit generator: 从C ++ 11开始std::shuffle()对随机位生成器采用右值引用:

template<class RandomIt, class URBG>
void shuffle(RandomIt first, RandomIt last, URBG&& g);

And so I might call it thus: 所以我可以这么称呼它:

std::vector<int> v = {...};
std::random_device rd;
std::mt19937 g(rd());
std::shuffle(v.begin(), v.end(), g);

This reveals an error in my understanding of C++ that I haven't been able to satisfy through reading this morning: what is gained by using an rvalue reference here? 这揭示了我对C ++的理解错误,我今天早上通过阅读无法满足:在这里使用右值引用可以获得什么? In other words, why is this not 换句话说,为什么不这样做

template<class RandomIt, class URBG>
void shuffle(RandomIt first, RandomIt last, URBG& g);

This is a forwarding reference, not an rvalue reference. 这是转发引用,而不是右值引用。 They have superficially similar syntax but can be differentiated by the base type being a deduced template parameter. 它们具有表面上相似的语法,但可以通过基本类型作为推导出的模板参数来区分。

Your suggested alternative would not compile if an rvalue was given for the third argument, whereas the forwarding reference allows any value category of argument. 如果为第三个参数给出了右值,则建议的替代方法将无法编译,而转发引用允许任何值类别的参数。

Using the cppreference example, it means you have both options of: 使用cppreference示例,这意味着您有两个选项:

std::mt19937 g(rd());
std::shuffle(v.begin(), v.end(), g);

and

std::shuffle(v.begin(), v.end(), std::mt19937(rd()));

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

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