std::ref
为您提供了某个内容的左值引用
。该引用被包装到一个对象中,然后您可以通过引用或值传递该对象。
下面的代码的预期行为是它打印i is 2
,但它打印i is 1
。 这是为什么?
为什么我有这样的期望?因为我通过 std::ref
将 tmp
传递给 wrapper
。在包装器中,然后通过值捕获引用。我会假设,由于我使用的是 std::ref
该值现在仍然是对 tmp
的引用。我正在更改 tmp
,并希望 f
反射(reflect)该更改。
#include <iostream>
#include <functional>
template<typename F>
auto wrapper(int i, F func) {
return [=]() { return func(i); };
}
void f(int i) {
std::cout << "i is " << i << '\n';
}
int main() {
int tmp = 1;
auto func = wrapper(std::ref(tmp), f);
tmp = 2;
func();
}
最佳答案
这不起作用的原因是您的 wrapper
函数采用 int
作为参数。
std::ref
返回一个 std::reference_wrapper
。
当您将其传递给需要 int
的函数时
您将获得隐式转换,并且不再使用引用。
如果您将函数签名更改为使用 std::reference_wrapper
,它将给出预期的结果。
#include <iostream>
#include <functional>
template<typename F>
auto wrapper(std::reference_wrapper<int> i, F func) {
return [=]() { return func(i); };
}
void f(int i) {
std::cout << "i is " << i << '\n';
}
int main() {
int tmp = 1;
auto func = wrapper(std::ref(tmp), f);
tmp = 2;
func();
}
关于c++ - 为什么我的 std::ref 不能按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60362608/