为了解决这些问题,C++ 标准库提供了三个有用的工具:std::cref、std::ref 和 std::reference_wrapper。这篇文章将深入探讨这些工具的用途、区别以及实际应用。
使用reference wrapper对象的get()方法,返回真正的引用(实际上reference wrapper是用指针表现出引用的所有特性,所以返回的应该是指针指向的对象)。 #include<iostream>#include<functional>template<typenameT>voidfunc(Ta){//a.add();//out:errora.get().add();//out:7 返回真正的引用}classtest{public:test(in...
问如何将std::reference_wrapper用作类成员?EN如果MyClass没有对Entity的有效引用,那么它是否处于有效状...
引用,其一变,都变。 当您希望将对象从std::reference包装器中取出时,可以使用get()成员函数。 #include <functional>//std::reference_wrapper#include <iostream>#include<vector>#include<string>intmain() { std::stringtom{"Tom"}; std::vector<std::reference_wrapper<std::string>>names{}; //std::v...
支持将reference wrapper对象转换为引用,且没有声明为explicit,所以支持隐式转换。 reference_wrapper的一个用例 reference wrapper的一大用处就是,stl容器提供的是value语义而不是reference语义,所以容器不支持元素为引用,而用reference_wrapper可以实现。以下代码摘自http://en.cppreference.com/w/cpp/utility/functional/...
reference_wrapper s,不像指针,没有空状态。它们必须 使用引用或另一个 reference_wrapper 进行初始化。 std::reference_wrapper<int> r; // Invalid 一个相似之处是浅拷贝语义:指针和 reference_wrapper 可以重新分配。 原文由 Columbo 发布,翻译遵循 CC BY-SA 3.0 许可协议 有...
例如,尝试直接输出std::reference_wrapper对象会失败,因为缺乏输出运算。即使是通用类型T,如arg1和arg2,如果类型推断不一致,也无法正确使用。因此,std::reference_wrapper主要适用于将引用作为“一流对象”在函数间传递,或在类内部保存对象引用,但最终仍需转化为原始类型使用。
std::reference_wrapperis used to pass objects by reference tostd::bind, the constructor ofstd::thread, or the helper functionsstd::make_pairandstd::make_tuple. It can also be used as a mechanism to store references inside standard containers (likestd::vector) that cannot normally hold refer...
std::reference_wrapper的一个有趣属性是它有一个operator T& () const noexcept;。这意味着即使它是一个真正的对象,它也可以自动转换为它所持有的引用。所以: 由于它是一个可复制的可分配对象,因此可以在容器中或其他不允许引用的情况下使用 由于它的operator T& () const noexcept;,它可以在任何可以使用引用...