c++ - 为什么我的 std::ref 不能按预期工作?

标签 c++ reference pass-by-reference higher-order-functions pass-by-value

std::ref 为您提供了某个内容的左值引用。该引用被包装到一个对象中,然后您可以通过引用或值传递该对象。

下面的代码的预期行为是它打印i is 2,但它打印i is 1这是为什么?

为什么我有这样的期望?因为我通过 std::reftmp 传递给 wrapper 。在包装器中,然后通过值捕获引用。我会假设,由于我使用的是 std::ref 该值现在仍然是对 tmp 的引用。我正在更改 tmp,并希望 f 反射(reflect)该更改。

Play with the code here.

#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/

相关文章:

c++ - 调用自定义排序函数的次数

c++ - 捕获鼠标光标图标 C++

c++ - 在 C++ 中创建类型 vector

c - 将 Int 值赋给 *Char 指针

函数调用后不需要的额外传递引用参数的 C++ 模式?

c++ - 通过单个函数返回另一个函数的多个参数

include - #using、#include 和 'assembly references'——它们是什么以及它们之间的关系?

r - 用另一个数据表中一列的值更新一个数据表中的一列 NA

C++11 传递 POD 类型的值比 const 引用差

r - R 中的修改时复制语义到底是什么?规范来源在哪里?