如何在C++中动态分配全局字符数组中的类实例?
How to dynamically allocate an instance of a class in a global char array in C++?
我有这个代码:
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()
调用析构函数,并在以后释放内存(如果需要(。
相关文章:
- 为什么静态数组成员变量在调用对象的实例后不显示任何内容?
- 如何在模板函数中实例化其长度使用模板参数的数组
- 从函数中全局删除并重新实例化数组结构,而无需在编译时知道数组的大小
- 我可以初始化 const 实例,以便我可以将其用作 const 来初始化数组吗?
- 结构数组的构造函数错误,错误消息:没有构造函数实例与参数列表匹配
- 有没有办法根据命令行参数定义数组大小?运行时与编译时实例化?
- 如何为包含另一个类实例的数组制作常量 getter?
- 是否允许使用初始值设定项列表将const数组引用实例化为构造函数参数
- 如何创建具有不同字符数组的多个类实例?
- 包含不同大小静态数组的类的多个实例
- 如何在C++中动态分配全局字符数组中的类实例?
- 我可以从initializer_list实例化数组吗?
- 在 C++ 结构内声明的数组 A[1] 创建多个实例
- 分割故障 - 遇到问题,创建新的数组实例
- 无法用const char *数组实例化模板
- 如何为字符串数组实例变量动态分配空间
- VC++错误:数组实例化的大小来自模板化的静态常量
- 声明对象数组:实例化它们
- 计数结构中的数组实例
- 数组实例化错误