Re: exception question,

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



cronusf@xxxxxxxxx wrote:
I have code like this (pseudocode):

MyClass::MyClass()
{
Array1 = new D3DXVECTOR3[MaxVertexCount];
Array2 = new USHORT[MaxIndexCount];

fx = gcnew Effect();
}

Suppose the constructor for Effect throws an exception. During the
stack unwinding, will Array1 and Array2 be deleted?

I put the delete[] code in the destructor and finalizer, but I noticed
(through trace statements) the destructor and finalizer is never
called. Do I need a try/finally here to make sure the memory is
deleted?

What's the type of Array1? Array2?

Unless it's some kind of smart pointer that takes care of deleting the
allocated memory, then you need to take responsibility for doing it.

The best option is to use a more intelligent data structure that takes care
of it for you, such as std::vector<D#DXVECTOR3> or std::vector<USHORT>,
rather than a bare pointer. When those objects go out of scope, their
destructors will be called automatically to clean up the memory allocation.

If you're set on handling it yourself instead of using a library component
to do it for you then yes, you need a try/catch around the code to handle
cleanup in the case of an exception thrown from the Effect constructor.

-cd


.



Relevant Pages

  • Re: exception question,
    ... but I think that Array1 and Array2 are defined like ... class MyClass ... exception safe, if an exception is thrown in the constructor, Array1 and ...
    (microsoft.public.dotnet.languages.vc)
  • Re: DbC & Exceptions & Style
    ... exception. ... Different ways the constructor can fail ... to avoid writing code that converts GUI data into objects, ... All domain objects must now provide a default constructor. ...
    (comp.object)
  • Re: Controlled types and exception safety
    ... >> propagate an exception. ... >> For an Adjust invoked as part of an assignment operation, ... But a user-defined constructor is ... a user-defined constructor has just turned on the ...
    (comp.lang.ada)
  • Re: is such exception handling approach good?
    ... There is nothing wrong with throwing from constructor. ... It may be a good design, it may not be a good design from user's point ... resource API to free-up the resource on exception. ... change something - that is not initialization. ...
    (microsoft.public.vc.language)
  • Re: Question concerning object-oriented programming
    ... constructor the inspectof the state fails to verify key ... Better yet the constructor could throw an exception. ... opposed to stateless) object can know if it is in an invalid state. ...
    (comp.programming)