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

标签 c++ function function-pointers

我在阅读一些文档时看到了这个:

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/

相关文章:

java - 将原生 uint8_t(Java 字节)转换为 int

C++ 类在不调用父构造函数的情况下构建和运行

c++ - 对 Class::Class/Function 的 undefined reference (OOP 初学者)

c++ - int(int, int) 样式模板函数类型语法

C++:在类中使用带有静态变量的 map 时遇到问题,我得到 undefined symbol

c++ - 从函数返回指针。一个指针的值未更新

c++ - C++中的空嵌套初始化列表

c++ - 这是内联函数的有效用法吗?

arrays - 定义返回数组的函数

c++ - libtorrent-rasterbar 无法使用磁力链接下载元数据