对象池模板

本文介绍了在嵌入式开发中使用对象池技术来管理内存,包括C++代码实现、CMake配置以及一个演示实例。展示了如何通过ObjectPool模板类动态分配和释放对象,以及可能出现的错误处理。
摘要由CSDN通过智能技术生成

概述

对象池的引入也是嵌入式开发的常用方法,也是内存预分配的一种,主要是用来隐藏全局对象的跟踪,通常预内存分配是通过数组来实现。

CMake配置

cmake_minimum_required(VERSION 3.5.1)

project(objpool)

add_executable(objpool objpool.cpp)



set(CMAKE_SYSTEM_NAME Linux)



SET(CMAKE_CXX_FLAGS "--std=c++11")

完整Demo

#include <iostream>

template<class T, size_t N>
class ObjectPool {
  private:
    T objects[N];
    size_t available[N];
    size_t top = 0;
  public:
    ObjectPool(): top(0) {
        for (size_t i = 0; i < N; i++) {
          available[i] = i;
        }
    }

    T& get() {
      if (top < N) {
        size_t idx = available[top++];
        return objects[idx];
      } else {
        throw std::runtime_error("All objects are in use");
      }
    }

    void free(const T& obj) {
      const T* ptr = &obj;
      size_t idx = (ptr - objects) / sizeof(T);
      if (idx < N) {
        if (top) {
          objects[idx].deinit();
          top--;
          available[top] = idx;
        } else {
          throw std::runtime_error("Some object was freed more than once");
        }
      } else {
        throw std::runtime_error("Freeing object that does not belong to the pool");
      }
    }
    size_t requested() const { return top; }
};


struct Point {
  int x, y;
  void deinit() { std::cout << "Hello " << x << ", " << y << "\n"; }
};

int main() {
  ObjectPool<Point, 10> points;

  Point& a = points.get(); 
  a.x = 10; a.y=20;
  std::cout << "Point a (" << a.x << ", " << a.y << ") initialized, requested " <<
    points.requested() << std::endl;

  Point& b = points.get(); 
  std::cout << "Point b (" << b.x << ", " << b.y << ") not initialized, requested " <<
    points.requested() << std::endl;

  points.free(a);
  std::cout << "Point a(" << a.x << ", " << a.y << ") returned, requested " <<
    points.requested() << std::endl;

  Point& c = points.get();
  std::cout << "Point c(" << c.x << ", " << c.y << ") not intialized, requested " <<
    points.requested() << std::endl;

  Point local;
  try {
    points.free(local);
  } catch (std::runtime_error e) {
    std::cout << "Exception caught: " << e.what() << std::endl;
  }
}

运行结果


我公司承接各类技术服务,主要聚焦于:stm32、单片机、嵌入式、QT应用开发、Web+Python+Django应用开发。欢迎合作。

  • 31
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

汉森教育

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值