boost functional

本文介绍了一个使用C++函数对象(fobject_t)的`int_processor`类,演示了如何处理整数范围并检测内存泄漏。通过`boost::function`实现自定义操作,并通过`std::for_each`遍历数组。重点展示了如何正确编译和使用,同时使用Valgrind进行内存泄漏检查。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <string>
#include <cassert>
#include <algorithm>
#include "boost/function.hpp"
typedef boost::function<void(int)>fobject_t;
class int_processor {
    const int min_;
    const int max_;
    bool &triggered_;
public:
    int_processor(int min, int max, bool &triggered)
        : min_(min)
        , max_(max)
        , triggered_(triggered)
    {}
    void operator() (int i) const {
        triggered_ = (i > max_ ) || (i < min_);
    }
};
void process_integers(const fobject_t &f) {
    static const int data[] = { 1, 2, 3, 4, 200 };
    std::for_each(std::begin(data), std::end(data), f);
}
int main() {
    bool is_triggered = false;
    int_processor fo(100, 200, is_triggered);
    process_integers(fo);
    std::cout << is_triggered << std::endl;

    return 0;
}

编译:

g++ -std=c++17 -g -o Test test.cpp -I ./ -I /opt/boost/boost_1_78_0 -L /opt/boost/boost_1_78_0/stage/lib  -lboost_thread -lboost_chrono -pthread

内存泄漏检测:

valgrind --tool=memcheck --leak-check=full --show-leak-kinds=all --undef-value-errors=no --log-file=log ./Test

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值