c++ - std::reference_wrapper 对比整数&

标签 c++ c++11 reference-wrapper

我正在试用 std::reference_wrapper使用以下代码段

int a = 42, b = 52;
std::tuple<std::reference_wrapper<int>> t = std::make_tuple(std::ref(a));

std::get<0>(t) = b;
std::cout << "t[0] = " << std::get<0>(t) << ", a = " << a << ", b = " << b
          << std::endl;

输出是t[0] = 52, a = 42, b = 52 ,这不足为奇。

但是,如果我只使用 auto对于 t , 即

int a = 42, b = 52;
auto t = std::make_tuple(std::ref(a));

std::get<0>(t) = b;
std::cout << "t[0] = " << std::get<0>(t) << ", a = " << a << ", b = " << b
          << std::endl;

然后我得到了t[0] = 52, a = 52, b = 52

看起来类型变成了int& .然后我有一些问题:

  1. 我以为std::ref给我们std::reference_wrapper而不是 &
  2. 我应该如何解释 & 的情况?以及为什么它不同于 std::reference_wrapper .
  3. 我还注意到,在 std::reference_wrapper 的情况下, std::get<0>(t) = 52;不编译。 (虽然在 & 的情况下是这样)。错误是“调用类‘std::__1::reference_wrapper’的私有(private)构造函数”。有人可以更详细地解释一下吗?

谢谢!!

最佳答案

  1. I thought std::ref gives us std::reference_wrapper rather than &?

这不是问题,但你想对了。

  1. How I should explain the case of & and why it is different from std::reference_wrapper.

std::reference_wrapper 参数传递给 std::make_tuple 时,生成的元组将具有引用成员而不是引用包装器。

行为上的差异是因为当您分配一个引用时,您修改了被引用的对象,而当您分配一个引用包装器时,您反而重新绑定(bind)包装器以引用另一个对象并且不修改被引用的对象。

I also noticed that, in the case of std::reference_wrapper, std::get<0>(t) = 52; does not compile. (While in the case of & it does). the error is "calling a private constructor of class 'std::__1::reference_wrapper'". Could someone explain that in more detail?

std::reference_wrapper 没有针对引用类型的赋值运算符。它只有另一个引用包装器的赋值运算符。 std::reference_wrapper 有一个接受左值但不接受右值的隐式转换构造函数。

这就是为什么您可以分配左值 b 而不能分配纯右值 52 的原因。这是一件好事,因为引用包装器无法延长临时对象的生命周期。

关于c++ - std::reference_wrapper 对比整数&,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65202911/

相关文章:

c++ - 为什么 reference_wrapper<string> 比较不起作用?

c++ - C++中的后自减和前自减运算符

c++ - 数组不保存初始化值

c++ - 类模板中文字运算符的Friend声明

c++ - 将 n 个二进制调用转换为 C++ 中的一个 n 元调用?

c++ - 为 std::unordered_map 中的 const std::reference_wrapper 重载 operator==

c++ - 在 C++ 中连接两个宽字符串的最快和/或最安全的方法?

c++ - 在 Google Mock 上调用重载函数

c++ - 模板化(或以某种方式自动)方法的返回值

c++ - 如何将 std::vector<std::reference_wrapper<T>> 转换为 std::vector<T>