我的第一个问题是当函数结束时,函数中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.
更多推荐
发布评论