【发布时间】:2018-01-11 00:31:27
【问题描述】:
我正在阅读一些文档并看到了这个:
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
【问题讨论】:
-
右值引用并不意味着“移动”。
-
@NicolBolas 我的意思是应用移动语义。它不会复制机器指令,而是“移动”它。
-
您可以拥有对函数的右值引用,但
Ret(Args...) &&不是。拼写为Ret (&&)(Args...)。 -
您既不能“复制”也不能“移动”机器指令。这些都与您的代码中发生的事情无关。您只是在“移动”一个函数指针。移动函数指针只是复制它(与所有基本类型相同)。
标签: c++ function function-pointers