首页 > 解决方案 > 将函数标识符作为右值引用传递并对其应用 std::move()

问题描述

考虑以下代码段

#include <iostream>
#include <functional>

using callback = std::function<double (double, double)>;


double sum (double a, double b) {
    return a + b;
}


int main (int argc, char *argv[]) {
    // Shouldn't this leave sum() in an invalid state?
    auto c = std::move(sum);

    std::cout << c(4, 5) << std::endl;
    std::cout << sum(4, 5) << std::endl;

    return EXIT_SUCCESS;
}

我正在转换sum为右值引用,将其存储在 中c,然后调用这两个函数而没有明显的不当行为。这是为什么?std::move不应该sum处于无效状态吗?

标签: c++stdmove

解决方案


您将指针移动到函数,而不是函数:

callback c = std::move(sum);

的使用在std::move这里是多余的。


推荐阅读