c++ - 这 std::ref 行为合乎逻辑吗?

标签 c++ c++11 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。

我错过了什么?

最佳答案

f2 的小修改提供线索:

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

现在这符合您的预期。

发生这种情况是因为 std::ref返回 std::reference_wrapper<>目的。 重新绑定(bind)包装器的赋值运算符。 (见 http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper/operator%3D)

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

f1情况下,一切正常,因为 std::reference_wrapper<T>提供到 T& 的转换运算符,它将绑定(bind)到 int 的隐式右侧s 隐含 operator+ .

关于c++ - 这 std::ref 行为合乎逻辑吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37101301/

相关文章:

c++ - 调用与方法同名的函数

c++ - 'function' 的外联定义与 'Class' 中的任何声明都不匹配

c++ - 为什么 deque 的 pop_front() 和 pop_back() 不是 noexcept?

javascript - 如何通过ref获取输入(StyledComponent)值

c# - 在数组上使用 'ref' 关键字

c++ - 我正在尝试制作字符串函数的 HashMap

c++ - 如何将 Qt qml 移植到带有 C++ 后端的 Web 服务器

c++ - 左值真的是非临时对象吗?

c++ - Rcpp 需要复制构造函数

perl (Statistics::PCA): 不能使用字符串 ("0") 作为 ARRAY ref while "strict refs"