c – 在堆栈上动态分配内存

c – 在堆栈上动态分配内存,第1张

概述有这样的代码: #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;} 输出是 有这样的代码:

#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 regionA *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 aspA->~A(); //call the destructor explicitly - must do it//Now deallocate the memory asdelete []buffer;

这是placement-new的最简单示例,它仅解释了语法.但故事并没有在这里结束;它是开始,并使其正常工作,缓冲区指向的内存必须正确对齐对象类型,在上面的例子中,我只是假设.在实际代码中,你不能做出这样危险的假设.现在阅读这个FAQ:

> What is “placement new” and why would I use it?

总结

以上是内存溢出为你收集整理的c – 在堆栈上动态分配内存全部内容,希望文章能够帮你解决c – 在堆栈上动态分配内存所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1222707.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存