c – 在堆栈上动态分配内存
发布时间:2020-12-16 10:46:00 所属栏目:百科 来源:网络整理
导读:有这样的代码: #include iostreamint main(){ int a; int* p = new (a) int(2); std::cout a std::endl; // delete p; error BLOCK TYPE IS INVALID std::cin.get(); return 0;} 输出是: 2 为什么可以在堆栈上动态分配内存? (我认为堆是正确的地方).并且,
有这样的代码:
#include <iostream> int main() { int a; int* p = new (&a) int(2); std::cout << a << std::endl; // delete p; error BLOCK TYPE IS INVALID std::cin.get(); return 0; } 输出是: 2 为什么可以在堆栈上动态分配内存? (我认为堆是正确的地方).并且,为什么在这种情况下删除操作符返回错误,但是新的操作符工作? 解决方法int* p = new (&a) int(2); 这称为placement-new.它不分配内存.它在一个内存中构造对象.在placement new中,用户指定new运算符构造对象的内存区域.在上面的代码中,您可以通过在new关键字之后写入(& a)表达式来指定内存区域.由于& a不是动态分配的内存,因此无法删除它: delete p; //runtime-error 它会给出运行时错误,它会尝试删除变量a所在的内存. 但是,如果您动态分配内存,则可以删除它.让我们假设,A是某类,那么你应该这样做: char *buffer = new char[sizeof(A)]; //allocate memory of sizeof(A); ///ASSUMPTION: the buffer is properly align as required by the type A //use placement-new to construct an object at the specified memory region A *pA = new (buffer) A(/*..parameters..*/); //... //incorrect way to delete the memory! //delete pA; //incorrect //before deleting the memory you should be calling the destructor explicitly as pA->~A(); //call the destructor explicitly - must do it //now deallocate the memory as delete []buffer; 这是placement-new的最简单示例,它仅解释了语法.但故事并没有在这里结束;它是开始,并使其正常工作,缓冲区指向的内存必须正确对齐对象类型,在上面的例子中,我只是假设.在实际代码中,你不能做出这样危险的假设.现在阅读这个FAQ: > What is “placement new” and why would I use it? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容