这个std :: ref行为是逻辑的吗? [英] Is this std::ref behaviour logical?

查看:231
本文介绍了这个std :: ref行为是逻辑的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑此代码:

#include <iostream>
#include <functional>

int xx = 7;

template<class T>
void f1(T arg)
{
    arg += xx;
}

template<class T>
void f2(T arg)
{
    arg = xx;
}

int main()
{
    int j;

    j=100;
    f1(std::ref(j));
    std::cout << j << std::endl;

    j=100;
    f2(std::ref(j));
    std::cout << j << std::endl;
}

执行时,此代码输出

107
100



第二个值是7而不是100。

I would have expected the second value to be 7 rather than 100.

我缺少什么?

推荐答案

f2 的小修改提供了线索:

A small modification to f2 provides the clue:

template<class T>
void f2(T arg)
{
    arg.get() = xx;
}

现在这是您期望的。

这是因为 std :: ref 返回一个 std :: reference_wrapper<> 。对其重新绑定包装器的赋值运算符。
(请参见 http://en.cppreference.com/w/cpp/ utility / functional / reference_wrapper / operator%3D

This has happened because std::ref returns a std::reference_wrapper<> object. The assignment operator of which rebinds the wrapper. (see http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper/operator%3D)

它不会对包装的引用进行赋值。

It does not make an assignment to the wrapped reference.

f1 的情况下,所有的工作正如你所期望的,因为 std :: reference_wrapper< T> 提供一个转换操作符到 T& ,它将绑定到 int 的隐式右侧c $ c> operator + 。

In the f1 case, all is working as you expected because a std::reference_wrapper<T> provides a conversion operator to T&, which will bind to the implicit right hand side of ints implicit operator+.

这篇关于这个std :: ref行为是逻辑的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆