【发布时间】:2011-03-25 01:43:53
【问题描述】:
我正在考虑我可能会写一些内存池/分配的东西,所以我想出了这个operator new 重载,我想用它来促进内存的重用。我想知道你们在我的实现(或任何其他可能的问题)中是否有任何问题。
#include <cstddef>
namespace ns {
struct renew_t { };
renew_t const renew;
}
template<typename T>
inline void * operator new(std::size_t size, T * p, ns::renew_t renew_constant) {
p->~T();
return p;
}
template<typename T>
inline void operator delete(void *, T *, ns::renew_t renew_constant) { }
可以这样使用
int main() {
foo * p(new foo()); // allocates memory and calls foo's default constructor
new(p, ns::renew) foo(42); // calls foo's destructor, then calls another of foo's constructors on the same memory
delete p; // calls foo's destructor and deallocates the memory
}
【问题讨论】:
-
赋值运算符是重用内存的好方法。
-
这不是一个好主意。内存管理系统非常有效(加上调整和正确)。除非您已经拥有大量运行时内存管理经验,否则自己编写是自找麻烦。
标签: c++ operator-overloading new-operator