“&”之间的区别,和std :: reference

编程入门 行业动态 更新时间:2024-10-27 15:23:56
本文介绍了“&”之间的区别,和std :: reference_wrapper?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下代码

#include <iostream> #include <vector> #include <functional> int main() { std::vector<double> v(5, 10.3); std::vector<double>& r = v; //std::vector<std::reference_wrapper<double>> r(v.begin(),v.end()); for (auto& i : v) i *= 3; for (auto i : r) std::cout << i << " "; std::cout << std::endl; }

我使用向量'r'的引用使用'&在第二行我注释掉我使用std :: reference_wrapper的C ++。两个都做同样的工作?但我认为必须有一个目的,使std :: reference_wrapper,即使我们有'&'来完成这项工作。

I am using reference of the vector 'r' using '&' operator and in the second line which I commented out I am using std::reference_wrapper of C++. Both do pretty much the same job? But I think there must be a purpose of making std::reference_wrapper even if we had '&' to do the job. can anyone explain please?

推荐答案

首先,两行

std::vector<double>& r = v; std::vector<std::reference_wrapper<double>> r(v.begin(),v.end());

不是指同样的事情。

其次,std :: reference_wrapper在通用编程中非常有用(一个是双引号向量的引用,另一个是双引号向量的引用) ie:templates)其中函数可以通过复制获取其参数,但是您仍然希望通过引用传递参数。或者,如果你想要一个容器有引用,但不能使用引用,因为它们不可复制或移动,那么std :: reference_wrapper可以做这项工作。

Second, std::reference_wrapper is useful in generic programming (ie: templates) where either a function might take its arguments by copy, but you still want to pass in an argument by reference. Or, if you want a container to have references, but can't use references because they aren't copyable or movable, then std::reference_wrapper can do the job.

本质上,std :: reference_wrapper的行为就像一个&除非它是可复制和可重新分配的

Essentially, std::reference_wrapper acts like a "&" reference, except that it's copyable and reassignable

更多推荐

“&amp;”之间的区别,和std :: reference

本文发布于:2023-08-04 17:26:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1298214.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:区别   amp   reference   std

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!