我想制作一个程序,现在可以说表示一个矩阵,该矩阵将由一个向量表示,该向量中的每个对象都将表示一个单元格示例:vector now 当构造矩阵时,构造函数接收要插入的单元格列表矩阵。列表的大小在编译时是未知的
我有兴趣在不使用堆内存的情况下创建这个矩阵。换句话说,不使用“new”或“delete”这个词创建对象,如果我不知道有多少对象要插入向量中,有什么办法吗?
我想制作一个程序,现在可以说表示一个矩阵,该矩阵将由一个向量表示,该向量中的每个对象都将表示一个单元格示例:vector now 当构造矩阵时,构造函数接收要插入的单元格列表矩阵。列表的大小在编译时是未知的
我有兴趣在不使用堆内存的情况下创建这个矩阵。换句话说,不使用“new”或“delete”这个词创建对象,如果我不知道有多少对象要插入向量中,有什么办法吗?
有一种特殊的方法可以使用 new 在堆栈中分配内存,或者使用所谓的放置 new 运算符作为静态存储。使用这个版本的 new,你保留了一块内存,并且你明确地告诉 new 你想在哪里存储一个特定的变量。它将按如下方式工作:
#include <new>
int main()
{
char buffer[500]; // chunk of memory
int p*;
p = new (buffer) int[10];
}
请注意,您需要包含新标头才能使用此特殊的新运算符。在这种情况下,当您使用自动存储时,内存将在离开声明它的块(主)时被释放。
参考资料:C++ Primer plus。第9章 第420页
如果不使用汇编指令直接(因此依赖于平台)操作程序/函数的堆栈帧,就没有标准的方法可以做到这一点——我非常不鼓励这样做。是什么阻止您使用堆?
用于alloca
获取指针,然后使用就地new
运算符:
void *p = alloca(sizeof(Class));
new (p) Whatever(arguments);
但是,请在使用前阅读alloca
手册页!要非常小心。正如 Jim Brissom 所说,alloca
不便携。
你不需要delete
。函数返回时内存将被释放
There is a way, it's very limiting and very unorthodox. You'll need to create a statically sized array of unsigned char
which form a memory pool. There will be a limit to the size of the list of objects. You'll need to overload a new
operator (and delete
operator) for that class to specifically target such a memory pool.
That said, there's really no good reason to go this route.
Well, if you don't want to use memory on the heap, where else do you want to get it from?
a) system dependant - you can ask the operating system to allocate some memory for you. But this is bad style (system dependant), and will use the same RAM... just in a different way allocated. For example, ::GlobalAlloc or ::LocalAlloc in Windows 32 will do such things if you are really interested in doing that.
b) memory mapped files - that might be interesting if you are asking because you think you'll have not enough RAM available and access time isn't an issue.
c) resort to C functions like malloc/free and cast the pointers... that is getting memory from the heap, just avoiding the "new" and "delete" keywords.
However, it is hard to tell what a "good" solution without information why you want to avoid new / delete. You have need for dynamic memory allocation, these two are the tools to do that.
Could you please explain/rephrase your question so you can get more precise answers?