Stack unwinding and destructors?

  • Thread starter Steven T. Hatton
  • Start date
S

Steven T. Hatton

On page 366 of TC++PL(SE) we are told " The destructor will be called
independently of whether the function is exited normally or exited because
an exception is thrown."

On page 382 the following appears:

"Consider the simple function f() that appears to have nothing to do with
exception handling:

void g(int);

void f()
{
string s;
//...
g(1);
g(2);
}

However, g() may throw an exception, so f() must contain code ensuring that
s is destroyed correctly in case of an exception."

These statements seem mutually inconsistent. Would it have been more
correct to use 'string* s = new string();' in place of "string s;"?
 
A

Andre Kostur

On page 366 of TC++PL(SE) we are told " The destructor will be called
independently of whether the function is exited normally or exited
because an exception is thrown."
Yep

On page 382 the following appears:

"Consider the simple function f() that appears to have nothing to do
with exception handling:

void g(int);

void f()
{
string s;
//...
g(1);
g(2);
}

However, g() may throw an exception, so f() must contain code ensuring
that s is destroyed correctly in case of an exception."

These statements seem mutually inconsistent. Would it have been more
correct to use 'string* s = new string();' in place of "string s;"?

More correct in what way? And how are the statements mutually
inconsistent?
 
J

John Harrison

On page 366 of TC++PL(SE) we are told " The destructor will be called
independently of whether the function is exited normally or exited
because
an exception is thrown."

On page 382 the following appears:

"Consider the simple function f() that appears to have nothing to do with
exception handling:

void g(int);

void f()
{
string s;
//...
g(1);
g(2);
}

However, g() may throw an exception, so f() must contain code ensuring
that
s is destroyed correctly in case of an exception."

I think 'must contain code' could be better expressed as 'the compiler
must place code'. There is nothing that the programmer need do to ensure
that the destructor for s is called, either by stack unwinding or normal
function exit.
These statements seem mutually inconsistent. Would it have been more
correct to use 'string* s = new string();' in place of "string s;"?

I don't think so, that would be a guaranteed memory leak, however the
function was exitted.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,023
Latest member
websitedesig25

Latest Threads

Top