Use a std::vector as object pool to store your objects and use indexes instead of pointers to access the objects:#include <iostream>#include <vector>struct Object { std::string name; std::size_t age; Object(const std::string &n, std::size_t a): name(n), age(a) {}};template<typename T>class Pool;template<typename T>class ObjectRef { Pool<T> &pool; std::size_t index; ObjectRef(Pool<T> &p, std::size_t i): pool(p), index(i) {}public: friend Pool<T>; T &operator*() { return pool.buffer[index]; } T *operator->() { return &pool.buffer[index]; }};template<typename T>class Pool { std::vector<T> buffer;public: friend ObjectRef<T>; Pool(std::size_t s = 250) { buffer.reserve(s); } template<typename... Ts> ObjectRef<T> newObject(Ts ...args) { buffer.emplace_back(args...); return ObjectRef<T>(*this, buffer.size() - 1); }};int main() { Pool<Object> objectPool(250); auto objectRef = objectPool.newObject("Name", 30); std::cout << objectRef->name; Pool<int> intPool(250); auto intRef = intPool.newObject(30); std::cout << *intRef;} 这篇关于堆中连续分配的对象的动态向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-16 02:31