Is this std::ref behaviour logical?
考虑以下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #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; } |
执行时,此代码输出
1 2 | 107 100 |
我希望第二个值是7而不是100。
我想念什么?
对
1 2 3 4 5 | template<class T> void f2(T arg) { arg.get() = xx; } |
这现在可以满足您的期望。
发生这种情况是因为
(请参阅http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper/operator=)
它不给包装的引用赋值。
在
因此,即使令人惊讶,这也是正常行为:
arg = xx;
本地
arg += xx;
隐式
)执行加法。
因此观察到的行为是正确的。