Topic: new[] failure behaviour


Author: herbs@cntc.com (Herb Sutter)
Date: 1997/04/03
Raw View
I've been looking through CD2 and can't find the answer to this question.  In
the following code:

 T* pt = 0;
 pt = new T[10];

if the fifth T constructor throws, what is the state and when (if ever) are
the first four constructed objects' dtors called?  For example, I would expect
that the first four T objects are automatically destroyed before the exception
is propagated out of new[].  If the exception is propagated with the four
fully constructed objects still intact, when (if ever) are they destroyed?

As an aside, I'm also assuming that the value of pt must be unchanged, since
the operator= has no opportunity to be called if an exception propagates out
of new[]... the corollary being that if an exception propagates out of new[],
all cleanup should already be done since delete[] can never be called, hence
my "I would expect" above.

---
Herb Sutter (mailto:herbs@cntc.com)

Current Network Technologies Corp. (http://www.cntc.com)
2695 North Sheridan Way, Suite 150, Mississauga ON Canada   L5K 2N6
Tel 416-805-9088   Fax 905-822-3824
---
[ comp.std.c++ is moderated.  To submit articles: Try just posting with your
                newsreader.  If that fails, use mailto:std-c++@ncar.ucar.edu
  comp.std.c++ FAQ: http://reality.sgi.com/austern/std-c++/faq.html
  Moderation policy: http://reality.sgi.com/austern/std-c++/policy.html
  Comments? mailto:std-c++-request@ncar.ucar.edu
]





Author: Alexandre Oliva <oliva@dcc.unicamp.br>
Date: 1997/04/03
Raw View
Herb Sutter writes:

>  pt = new T[10];

> if the fifth T constructor throws, what is the state and when (if
> ever) are the first four constructed objects' dtors called?

[except.ctor] paragraph 2 says that the constructed elements of the
array will be destroyed, and the deallocation function is invoked to
free the memory.

> As an aside, I'm also assuming that the value of pt must be
> unchanged, since the operator= has no opportunity to be called if an
> exception propagates out of new[]...

Correct.

--
Alexandre Oliva
mailto:oliva@dcc.unicamp.br mailto:aoliva@acm.org
Universidade Estadual de Campinas, SP, Brasil
---
[ comp.std.c++ is moderated.  To submit articles: Try just posting with your
                newsreader.  If that fails, use mailto:std-c++@ncar.ucar.edu
  comp.std.c++ FAQ: http://reality.sgi.com/austern/std-c++/faq.html
  Moderation policy: http://reality.sgi.com/austern/std-c++/policy.html
  Comments? mailto:std-c++-request@ncar.ucar.edu
]