when memory will be released?

I have created a code block, like this.

proc()
{
    Z* z = new Z();
}

now the pointer declared inside method proc will have scope only till proc. I want to ask when the DTOR for z will be called automatically. whether when the controls come out of the method proc or when my application is closed.


The destructor will not be called at all. The memory used by *z will be leaked until the application is closed (at which point the operating system will reclaim all memory used by your process).

To avoid the leak, you have to call delete at some point or, better yet, use smart pointers.


This is a memory leak. What you probably should have is:

void
proc()
{
    Z z;
}

and skip the dynamic allocation. If an object's lifetime corresponds to its scope, you rarely need dynamic allocation.

If for some reason you do need dynamic allocation (eg because of polymorphism), then you should use some sort of smart pointer; std::auto_ptr works well here, and things like scoped_ptr , if you have them, may be even better.


This is one of the fundamentals in C++.

Dynamic allocation

In your case, memory allocation and consequent constructor call for Z will happen on new :

Z* z = new Z();

The opposite part for destruction and memory deallocation will happen on delete :

delete z;

But since your code don't have it, memory deallocation will never happen, plus you will lose the pointer z having no possibility deallocating the object in future. This is typical memory leak.

Declaration

On the other hand, if you declare object like this:

Z z;

Memory allocation and constructor will be called immediately right here at declaration point, and when object's scope of existence is finished (ie at the end of the function) destructor will be called automatically and memory will be deallocated.

Dynamic allocation vs Declaration

I will not go into debates about what is better and what is not, but rather will provide the excerpt from one of the articles that is linked below:

Unlike declarations, which load data onto the programs data segment, dynamic allocation creates new usable space on the programs STACK (an area of RAM specifically allocated to that program).

FYI : Stack = Performance, but not always the best solution.

References

For your pleasure : tic tac toe.

链接地址: http://www.djcxy.com/p/13884.html

上一篇: 是否更快地访问静态或动态分配的内存?

下一篇: 当内存将被释放?