C++库std::ref

1 介绍

std::ref 是一个函数模板,它返回一个 std::reference_wrapper 对象,这个对象包装了一个引用。std::ref 的主要用途是在需要按引用传递参数的地方,而标准库算法和函数对象通常会按值传递参数。


2 语法

template< class T >
std::reference_wrapper<T> ref( T& t ) noexcept;

3 示例

头文件

#include <functional>

以下示例展示了如何使用 std::ref 包装一个引用并传递给一个函数对象:

#include <iostream>
#include <functional>

void print(int& n) {
    std::cout << n << std::endl;
}

int main() {
    int x = 10;
    std::function<void()> func = std::bind(print, std::ref(x));
    func(); // 输出: 10
    return 0;
}


4 使用场景

4.1 多线程编程

在多线程编程中,有时需要将引用传递给线程函数。std::ref 在这种情况下非常有用:

#include <iostream>
#include <thread>
#include <functional>

void thread_func(int& n) {
    n += 1;
}

int main() {
    int x = 10;
    std::thread t(thread_func, std::ref(x));
    t.join();
    
    std::cout << x << std::endl; // 输出: 11
    return 0;
}

4.2 实现回调机制

在回调机制中,可以使用 std::ref 传递引用以便在回调函数中修改外部变量:

#include <iostream>
#include <functional>

void callback(int& n) {
    n *= 2;
}

void register_callback(std::function<void(int&)> cb, int& value) {
    cb(value);
}

int main() {
    int x = 5;
    register_callback(callback, std::ref(x));
    
    std::cout << x << std::endl; // 输出: 10
    return 0;
}

4.3 标准库算法

当使用标准库算法时,如果希望算法对容器中的元素进行修改,可以使用 std::ref:

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>

void increment(int& n) {
    ++n;
}

int main() {
    std::vector<int> vec{1, 2, 3, 4, 5};
    std::for_each(vec.begin(), vec.end(), std::ref(increment));
    
    for (const auto& elem : vec) {
        std::cout << elem << " "; // 输出: 2 3 4 5 6
    }
    return 0;
}

4.4 绑定函数参数

在使用 std::bind 绑定函数参数时,如果需要绑定一个引用参数,可以使用 std::ref

复制代码
#include <iostream>
#include <functional>

void update_value(int& n, int new_value) {
    n = new_value;
}

int main() {
    int x = 5;
    auto bound_func = std::bind(update_value, std::ref(x), 10);
    bound_func();
    
    std::cout << x << std::endl; // 输出: 10
    return 0;
}

5 注意事项

5.1 与直接引用&的区别

直接传引用std::ref 各有优劣。直接传引用简单直观,适用于函数参数传递和性能优化场景,而 std::ref 则提供了更灵活的方式,使得引用能够在标准库算法、函数对象和多线程编程中方便地传递。在实际编程中,选择哪种方式取决于具体的使用场景和需求。

特性直接传引用&std::ref
使用场景函数参数、性能优化标准库算法、函数对象、多线程编程
易用性简单直接需要额外的包装操作
适用范围仅限函数参数标准库算法、函数对象、回调、多线程编程
安全性容易理解和控制需要注意引用对象的生命周期
性能最优有少量的包装开销

示例比较

#include <iostream>

void increment(int& n) {
    ++n;
}

int main() {
    int x = 10;
    increment(x);
    std::cout << "直接引用:"<< x << std::endl; // 输出: 11
    
    x = 10;
    auto func = std::bind(increment, std::ref(x));
    func();
    std::cout <<"使用std::ref:"<< x << std::endl; // 输出: 11
    
    return 0;
}

在实际应用中,能用直接引用就使用`直接引用`
当:
1.使用`与标准库算法`,
2.使用std::bind或其他类似工具
3.多线程编程中将引用传递给线程函数

直接传引用不适用,使用`std::ref`

5.2 引用生命周期

确保被引用的对象在 std::reference_wrapper 的生命周期内有效。如果对象被销毁,引用将变为悬空引用,导致未定义行为:

#include <iostream>
#include <functional>

int main() {
    std::function<void()> func;
    {
        int x = 10;
        func = std::bind([](int& n){ std::cout << n << std::endl; }, std::ref(x));
    }
    // func(); // 未定义行为,因为 x 已经被销毁
    
    return 0;
}

5.3 与标准库容器的结合

使用std::ref包装的引用不能直接存储在标准库容器中,因为容器存储的是而不是引用。解决方案是存储std::reference_wrapper,不过这种用法比较少。

#include <iostream>
#include <vector>
#include <functional>

int main() {
    int x = 10;
    int y = 20;
    
    std::vector<std::reference_wrapper<int>> vec{std::ref(x), std::ref(y)};
    for (auto& elem : vec) {
        elem.get() += 1;
    }
    
    std::cout << x << " " << y << std::endl; // 输出: 11 21
    return 0;
}

C++中的std::bind是一个函数模板,用于创建一个可调用对象(函数对象或成员函数指针),并绑定其参数。它可以将一个函数或成员函数与一组参数绑定在一起,形成一个新的可调用对象。 std::bind的基本语法如下: ```cpp std::bind(Function, args...) ``` 其中,Function是要绑定的函数或成员函数指针,args是要绑定的参数。 使用std::bind可以实现以下功能: 1. 绑定普通函数的部分参数,生成一个新的可调用对象。 2. 绑定成员函数的对象指针和部分参数,生成一个新的可调用对象。 3. 绑定成员函数的对象引用和部分参数,生成一个新的可调用对象。 下面是一些示例: 1. 绑定普通函数的部分参数: ```cpp #include <iostream> #include <functional> void printSum(int a, int b) { std::cout << "Sum: " << a + b << std::endl; } int main() { auto printSumWith5 = std::bind(printSum, 5, std::placeholders::_1); printSumWith5(10); // 输出:Sum: 15 return 0; } ``` 2. 绑定成员函数的对象指针和部分参数: ```cpp #include <iostream> #include <functional> class MyClass { public: void printProduct(int a, int b) { std::cout << "Product: " << a * b << std::endl; } }; int main() { MyClass obj; auto printProductWith2 = std::bind(&MyClass::printProduct, &obj, std::placeholders::_1); printProductWith2(5); // 输出:Product: 10 return 0; } ``` 3. 绑定成员函数的对象引用和部分参数: ```cpp #include <iostream> #include <functional> class MyClass { public: void printDifference(int a, int b) { std::cout << "Difference: " << a - b << std::endl; } }; int main() { MyClass obj; auto printDifferenceWith3 = std::bind(&MyClass::printDifference, std::ref(obj), std::placeholders::_1); printDifferenceWith3(7); // 输出:Difference: 4 return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值