一、模板版头文件monopoly_allocator.hpp#ifndefMONOPOLY_ALLOCATOR_HPP#defineMONOPOLY_ALLOCATOR_HPP#includemutex#includecondition_variable#includevector#includememory#includealgorithmtemplatetypenameTclassMonopolyAllocator{public:classData;usingDataPtrstd::shared_ptrData;classData{public:Data(MonopolyAllocator*mgr):manager_(mgr){}std::shared_ptrTdata(){returndata_;}voidrelease();boolavailable_true;std::shared_ptrTdata_;private:MonopolyAllocator*manager_;};MonopolyAllocator(intsize){capacity_size;available_size;pool_.resize(size);for(inti0;isize;i){pool_[i]std::make_sharedData(this);}}DataPtrquery(inttimeout_ms5000){std::unique_lockstd::mutexlock(mtx_);boolhas_itemcv_.wait_for(lock,std::chrono::milliseconds(timeout_ms),[this](){returnavailable_0;});if(!has_item)returnnullptr;autoitstd::find_if(pool_.begin(),pool_.end(),[](DataPtrd){returnd-available_;});if(itpool_.end())returnnullptr;(*it)-available_false;available_--;return*it;}private:voidrelease(Data*d){std::lock_guardstd::mutexlock(mtx_);if(!d-available_){d-available_true;available_;cv_.notify_one();}}std::vectorDataPtrpool_;std::mutex mtx_;std::condition_variable cv_;intcapacity_;intavailable_;};templatetypenameTinlinevoidMonopolyAllocatorT::Data::release(){manager_-release(this);}#endif二、main.cpp模板使用演示支持任意类型#includeiostream#includememory#includemonopoly_allocator.hppusingnamespacestd;intmain(){// // 模板版可以放 float / int / 结构体 / Tensor 等// shared_ptrMonopolyAllocatorfloattensor_allocator_make_sharedMonopolyAllocatorfloat(2);// // 1. 获取一块数据// autoitem1tensor_allocator_-query();if(item1){cout获取 item1 成功endl;// 分配内存if(!item1-data()){item1-data()make_sharedfloat(640*640*3);cout分配内存成功endl;}float*ptritem1-data().get();ptr[0]1.0f;ptr[1]2.0f;cout赋值ptr[0] ptr[0], ptr[1] ptr[1]endl;}// // 2. 获取第二个// autoitem2tensor_allocator_-query();if(item2){cout获取 item2 成功endl;}// // 3. 释放 → 复用// item1-release();cout释放 item1 成功endl;autoitem3tensor_allocator_-query();if(item3){cout获取 item3 成功复用endl;}// 释放所有item2-release();item3-release();cout程序运行完成endl;return0;}三、超强亮点现在支持任意类型了例子1管理 floatshared_ptrMonopolyAllocatorfloatalloc;例子2管理 intshared_ptrMonopolyAllocatorintalloc;例子3管理自定义结构体structMyData{floatx,y,z;};shared_ptrMonopolyAllocatorMyDataalloc;例子4管理你的 TRT::Tensor和你工程一模一样shared_ptrMonopolyAllocatorTRT::Tensortensor_allocator_;tensor_allocator_make_sharedMonopolyAllocatorTRT::Tensor(max_batch_size*2);四、总结超级清晰从固定 float 类型 → 通用模板类支持任意数据类型逻辑完全不变性能不变线程安全不变智能指针管理分配器 管理数据 管理内存可直接用于你的 YOLO/TensorRT 工程写法和你项目里的TRT::Tensor分配器完全一致