考虑这段代码:
#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/