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 (e.g. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With