将引用(右值)移动到函数

Move reference (rvalue) to function

本文关键字:移动 函数 右值 引用      更新时间:2023-10-16

我正在阅读一些文档并看到以下内容:

template<class Ret, class... Args>
struct is_function<Ret(Args...) &&> : std::true_type {};

引自:http://en.cppreference.com/w/cpp/types/is_function

如何对函数进行右值引用?

据我了解,函数没有存储生命周期。有人可以解释一下吗?我理解引用和指针,但如何"移动"函数?

我写了这段代码,它编译并运行起来:

#include <iostream>
using namespace std;
int foo(int num) {
    return num + 1;
}
int main() {
    int (*bar1)(int) = &foo;
    cout << bar1(1) << endl;
    int (&bar2)(int) = foo;
    cout << bar2(2) << endl;
    auto bar3 = std::move(bar2); // ????
    cout << bar3(3) << endl;
    cout << bar2(2) << endl;
    int (&&bar4)(int) = foo; // ????
    cout << bar4(4) << endl;
}

假设您是否可以将函数作为字节码/操作码存储在内存中,并"移动"它。CPU 不会阻止它运行吗?

编辑:@NicolBolas纠正了我的误解,但这是我另一个"问题"的答案:函数的右值引用

如何对函数进行右值引用?

这不是这个意思。

Ret(Args...) &&末尾的&&是指成员函数具有右值this的能力。因此,专用化适用于将Ret作为返回值、Args作为其参数并使用右值this的函数类型。

所以它不是"对函数的右值引用"。这是一个采用右值this的函数。