std::function_ref ​

什么是 std::function_ref ​

std::function_ref 是 C++26 引入的非拥有型(non-owning)函数包装器,定义在 <functional> 头文件中。它类似于 std::string_view 之于 std::string——只是引用一个可调用对象,不拥有它、不拷贝它、不分配内存。

std::function 和 std::move_only_function 都拥有(own)被包装的可调用对象,可能涉及堆分配。std::function_ref 只存储一个指针和一个函数指针,开销极小,适合作为函数参数传递临时的可调用对象。

cpp
#include <functional>

void apply(std::function_ref<int(int)> f, int x) {
    std::cout << f(x) << std::endl;
}

// 调用时不会拷贝 lambda,只是引用它
apply([](int x) { return x * 2; }, 5);

四种函数包装器对比 ​

特性functionmove_only_functioncopyable_functionfunction_ref
所有权拥有拥有拥有不拥有(引用)
可拷贝是否是是(浅拷贝)
堆分配可能可能可能不会
大小较大较大较大极小(2个指针)
cv/ref/noexcept不支持支持支持支持
空状态有有有没有
适用场景存储回调存储仅移动回调存储可拷贝回调传递回调参数

基本示例 ​

cpp
#include <iostream>
#include <functional>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>

// ============================
// 示例1:作为函数参数
// ============================

// function_ref 作为参数——不拥有可调用对象
void for_each_value(const std::vector<int>& vec,
                    std::function_ref<void(int)> callback) {
    for (int v : vec) {
        callback(v);
    }
}

void param_demo() {
    std::vector<int> data = {1, 2, 3, 4, 5};

    // 传入 lambda——不会拷贝或分配堆内存
    for_each_value(data, [](int v) {
        std::cout << v << " ";
    });
    std::cout << std::endl;

    // 传入带捕获的 lambda
    int sum = 0;
    for_each_value(data, [&sum](int v) {
        sum += v;
    });
    std::cout << "求和: " << sum << std::endl;
}

// ============================
// 示例2:传递普通函数
// ============================

void print_value(int v) {
    std::cout << "  " << v << std::endl;
}

void function_ptr_demo() {
    std::vector<int> data = {10, 20, 30};

    // 传入普通函数指针
    for_each_value(data, print_value);
}

// ============================
// 示例3:传递函数对象
// ============================

struct Multiplier {
    int factor;
    int operator()(int x) const { return x * factor; }
};

int transform_and_sum(const std::vector<int>& vec,
                      std::function_ref<int(int) const> transform) {
    int sum = 0;
    for (int v : vec) {
        sum += transform(v);
    }
    return sum;
}

void functor_demo() {
    std::vector<int> data = {1, 2, 3, 4, 5};

    Multiplier mul{3};
    int result = transform_and_sum(data, mul);
    std::cout << "乘以3后求和: " << result << std::endl;  // 45

    // lambda 也可以
    result = transform_and_sum(data, [](int x) { return x * x; });
    std::cout << "平方后求和: " << result << std::endl;  // 55
}

// ============================
// 示例4:对比模板参数
// ============================

// 模板方式——每个不同的可调用对象生成一个实例化
template<typename F>
void apply_template(const std::vector<int>& vec, F&& f) {
    for (int v : vec) f(v);
}

// function_ref 方式——不会代码膨胀
void apply_ref(const std::vector<int>& vec,
               std::function_ref<void(int)> f) {
    for (int v : vec) f(v);
}

// std::function 方式——可能堆分配
void apply_func(const std::vector<int>& vec,
                std::function<void(int)> f) {
    for (int v : vec) f(v);
}

void comparison_demo() {
    std::vector<int> data = {1, 2, 3};

    // 三种方式都能工作
    apply_template(data, [](int v) { std::cout << v << " "; });
    std::cout << std::endl;

    apply_ref(data, [](int v) { std::cout << v << " "; });
    std::cout << std::endl;

    apply_func(data, [](int v) { std::cout << v << " "; });
    std::cout << std::endl;
}

// ============================
// 示例5:高阶函数
// ============================

int apply_twice(std::function_ref<int(int)> f, int x) {
    return f(f(x));
}

void higher_order_demo() {
    auto double_it = [](int x) { return x * 2; };
    auto add_one = [](int x) { return x + 1; };

    std::cout << "double twice(3): " << apply_twice(double_it, 3) << std::endl;  // 12
    std::cout << "add1 twice(3): " << apply_twice(add_one, 3) << std::endl;      // 5
}

// ============================
// 示例6:没有空状态
// ============================

void no_null_demo() {
    // function_ref 没有默认构造函数——不能为空
    // std::function_ref<void()> ref;  // 编译错误

    // 必须在构造时就绑定一个可调用对象
    auto lambda = [] { std::cout << "总是有效" << std::endl; };
    std::function_ref<void()> ref = lambda;
    ref();

    // 不需要检查是否为空——它总是有效的
}

// ============================
// 示例7:生命周期注意事项
// ============================

void lifetime_demo() {
    // 正确:lambda 的生命周期覆盖 function_ref 的使用
    auto lambda = [](int x) { return x + 1; };
    std::function_ref<int(int)> ref = lambda;
    std::cout << "正确使用: " << ref(10) << std::endl;

    // 危险:不要让 function_ref 超过被引用对象的生命周期
    // std::function_ref<int(int)> make_dangling() {
    //     auto local = [](int x) { return x; };
    //     return local;  // 危险!local 在函数结束后销毁
    // }
}

int main() {
    std::cout << "=== 函数参数 ===" << std::endl;
    param_demo();

    std::cout << "\n=== 函数指针 ===" << std::endl;
    function_ptr_demo();

    std::cout << "\n=== 函数对象 ===" << std::endl;
    functor_demo();

    std::cout << "\n=== 对比 ===" << std::endl;
    comparison_demo();

    std::cout << "\n=== 高阶函数 ===" << std::endl;
    higher_order_demo();

    std::cout << "\n=== 无空状态 ===" << std::endl;
    no_null_demo();

    std::cout << "\n=== 生命周期 ===" << std::endl;
    lifetime_demo();

    return 0;
}

何时使用 function_ref ​

场景推荐方式
函数参数接受回调(不存储)std::function_ref
需要存储回调(可拷贝)std::copyable_function 或 std::function
需要存储回调(仅移动)std::move_only_function
泛型代码(编译期多态)模板参数

适用场景 ​

  • 函数参数接受可调用对象(不需要存储)
  • 替代模板参数避免代码膨胀
  • 替代 std::function 避免堆分配
  • 高阶函数的参数
  • 算法的自定义操作

常见问题 ​

function_ref 可以为空吗?

不可以。function_ref 没有默认构造函数,也不接受 nullptr。它总是引用一个有效的可调用对象。

function_ref 可以存储吗?

技术上可以,但不推荐。function_ref 不拥有被引用的对象,如果被引用对象被销毁,function_ref 会变成悬垂引用。它应该主要用作函数参数。

function_ref 的大小是多少?

通常是两个指针大小(16字节,64位平台)——一个对象指针和一个调用函数指针。远小于 std::function。

function_ref 和 std::span 类似吗?

概念上类似。std::span 是数组的非拥有视图,function_ref 是可调用对象的非拥有视图。两者都不拥有底层数据,都应注意生命周期。

注意事项 ​

  • 不拥有被引用的可调用对象——注意生命周期
  • 没有默认构造函数,不能为空
  • 不要将 function_ref 存储为成员变量(除非能保证生命周期)
  • 主要用作函数参数
  • C++26 特性,编译器支持可能有限
  • 需要 <functional> 头文件

总结 ​

std::function_ref 是 C++26 引入的非拥有型轻量函数包装器,类似于 std::string_view 对 std::string 的关系。它只引用一个可调用对象,不拥有、不拷贝、不分配堆内存,大小只有两个指针。它没有空状态——总是引用有效的可调用对象。function_ref 的理想用途是作为函数参数接受可调用对象,替代模板参数(避免代码膨胀)或 std::function(避免堆分配)。使用时必须确保被引用的可调用对象的生命周期覆盖 function_ref 的使用期。