新的内存分配(memory allocation by new)

编程入门 行业动态 更新时间:2024-10-25 22:26:00
新的内存分配(memory allocation by new)

我的第一个问题是当函数结束时,函数中new分配的内存会被自动删除(释放)。

int* foo() { int *a = new int; //memory allocated for an int *a = 3; return (a); }//function ends -- is memory for integer still allocated.

如果在函数结束后自动取消分配内存,那么我的下一个代码不应该给出一些与访问不属于我的内存有关的错误。

int main() { int *x = foo(); cout<<*x; }

My first question is does the memory allocated by new in a function gets automatically deleted(deallocated) when the function ends.

int* foo() { int *a = new int; //memory allocated for an int *a = 3; return (a); }//function ends -- is memory for integer still allocated.

If the memory is de-allocated automatically after the function ends, then shouldn't my next code give some error relating to accessing the memory which does not belong to me.

int main() { int *x = foo(); cout<<*x; }

最满意答案

不,它肯定没有。 每个new都必须与delete平衡。 (并且,为了避免任何未来的疑问,任何new[]必须与delete[] )平衡。

C ++中的构造允许在容器对象超出范围时有效释放内存。 看看std::shared_ptr和std::unique_ptr 。

No it certainly does not. Every new has to be balanced with a delete. (And, to avoid any future doubt, any new[] has to be balanced with a delete[]).

There are constructs in C++ that will allow the effective release of memory once a container object has gone out of scope. Have a look at std::shared_ptr and std::unique_ptr.

更多推荐

本文发布于:2023-08-01 11:26:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1358096.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:分配   内存   allocation   memory

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!