Re: noob question - destructors - freeing memory...
On Dec 31, 4:37 am, someone <newsbo...@gmail.com> wrote:
On 12/31/2011 04:50 AM, Garrett Hartshaw wrote:
On Sat, 31 Dec 2011 02:43:28 +0100, someone <newsbo...@gmail.com> wrote=
:
Hi
Please advice, thank you!
A statically constructed object will be destroyed when the scope is lef=
t.
e.g destructors will be called in:
int main()
{
Derived d;
return 0;
}
Ah, stupid me. I thought I had tried the above, and that it didn't work
- thank you very much. My mistake, maybe also in reply to MikeWhy...
A dynamically constructed object (created using new) is destroyed when
delete is called.
e.g destructors called in this:
int main()
{
Base * b = new Derived();
delete b;
return 0;
}
but not this:
int main()
{
Base * b = new Derived();
return 0;
}
Yes, this is clear now, the static thing was a brain-something that hit
me...
When exit(int) is called, the program is terminated *without unwinding
the stack* so no destructors are called.
Yes, clear.
When a execption is thrown and not caught, the program is terminated
*with stack unwinding*, so static objects are destroyed.
Aah, only static objects... DAMN...
Note: int main()
{
Base * b = new Derived();
throw std::exception();
delete b;
return 0;
}
In the above, the delete expression is never reached, so destructors ar=
e
not called.
That is a big problem/issue in my program, I think...
So if I allocate memory in my constructor, and I never call the
destructor and I keep running and exiting, running and exiting the
program, then I end up using all my memory because I never free'd it?
If this is an issue, a smart pointer (boost::shared_ptr,
boost::scoped_ptr, etc:) should be used.
Ooh, damn...
I hoped, I could avoid having to learn something new and timeconsuming
like boost...
Isn't there an easier solution without including more libraries?
std::auto_ptr
though I believe this is now deprecated. Hasn't been removed though
and does the job.