如何在C++中动态分配全局字符数组中的类实例?

How to dynamically allocate an instance of a class in a global char array in C++?

本文关键字:数组 实例 字符 全局 C++ 动态分配      更新时间:2023-10-16

我有这个代码:

const int size = 1024;
char pool[size];
int nextFree = 0;
class A
{
...
}

我必须扩展class A的功能,以便当客户端调用此类的动态分配时:

A* a = new A();

则要放置在全局数组中的实例pool

我正在考虑使用placement new超载operator new和内部。像这样:

class A
{
...
void* operator new(size_t size)
{
void * pInt = ::new (&pool[nextFree]) A();
nextFree += size;
return pInt;
}
...
}

它一直工作到释放动态分配,编译器会抛出错误:"free((:无效指针"。我也尝试超载operator delete但没有成功。

任何想法应该如何以正确的方式完成?

据我了解,您希望将对象放置在池中,但对于最终用户来说,它应该看起来像是将对象放在堆上一样。在这种情况下,您可以简单地执行此操作:

#include <iostream>
const int size = 1024;
char pool[size];
int nextFree = 0;
class A
{
public:
int i = 123; // some data
A() { std::cout << "constructorn"; }
~A() { std::cout << "destructorn"; }
static void* operator new(std::size_t size) noexcept
{
void *ptr = &pool[nextFree];
nextFree += size;
return ptr;
}
static void operator delete(void* ptr, std::size_t size) noexcept
{
//memset(ptr, 0, size); for example
}
};
int main()
{
A* a = new A();
std::cout << std::boolalpha << (a == reinterpret_cast<A*>(&pool[0])) << std::endl;
delete a;
}

https://ideone.com/zMW86t

放置 new 不会分配内存,它只是在已分配的内存上调用构造函数,因此删除没有意义。 您只是假设在对象被销毁时使用T::~T()调用析构函数,并在以后释放内存(如果需要(。