我在阅读一些文档时看到了这个:
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 纠正了我的误解,但这是我另一个“问题”的答案:rvalue reference to function
最佳答案
How can you have a rvalue reference to a function?
那不是那个意思。
Ret(Args...) &&
最后的&&
指的是a member function to have an rvalue this
的能力.因此,该特化适用于以 Ret
作为返回值、以 Args
作为参数并使用右值 this
的函数类型。
所以它不是“函数的右值引用”。这是一个接受右值 this
的函数。
关于c++ - 将引用(右值)移动到函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48198226/