473,395 Members | 1,863 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

exception question,

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?
Aug 7 '08 #1
4 1122
Do I need a try/finally here to make sure the memory is
deleted?
I meant try/catch, as I only want to free the memory if an exception
occurred.

Aug 7 '08 #2
cr*****@gmail.com 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#DXVECTOR3or 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
Aug 7 '08 #3

<cr*****@gmail.comha scritto nel messaggio
news:d6**********************************@t1g2000p ra.googlegroups.com...
>I have code like this (pseudocode):

MyClass::MyClass()
{
Array1 = new D3DXVECTOR3[MaxVertexCount];
Array2 = new USHORT[MaxIndexCount];
Correct me if I'm wrong, but I think that Array1 and Array2 are defined like
this:

<code>

class MyClass
{
...

D3DXVECTOR3 * Array1;
USHORT * Array2;
...

};

</code>

In that case, the answer to your question is "no": your code is not
exception safe, if an exception is thrown in the constructor, Array1 and
Array2 are leaked.

As Carl already wrote, I think the best approach is to use std::vector
instead of new[] (and delete[]).

e.g.

<code>

#include <vector// Use std::vector

class MyClass
{
....

std::vector< D3DXVECTOR3 Array1;
std::vector< USHORT Array2;

...
};
MyClass::MyClass()
: Array1( MaxVertexCount ), // Construct the std::vector arrays
Array2( MaxIndexCount )
{
... other code
fx = gcnew Effect();
}

</code>

Note that std::vector can change size at run-time (unlike arrays allocated
with new[], which are fixed-size), so you may also want to initialize empty
vectors, and use .push_back() method to add new data to vector.

There is a similar case if you have something like a *raw* pointer to some
class as data member, e.g.:

<code>

class MyClass
{
...
X * pX; // X is some embedded class (raw pointer)
};

MyClass::MyClass()
{
pX = new X(...);
....
}

</code>

The above code is exception unsafe, and if some exception is thrown in the
constructor, the instance of X allocated on the heap is leaked.
You should instead use a smart pointer like shared_ptr in this case:

<code>

class MyClass
{
...
shared_ptr< X spX; // smart pointer to X
};

MyClass::MyClass()
spX( new X(...) ) // Create new X
{
...
}

</code>

In general, in modern C++, you should use container classes like std::vector
instead of raw arrays (new[]/delete[]), and smart pointers (like shared_ptr)
instead of raw pointers. This will make your programming life easier: you
will have less leaks, and more robust and exception-safe code.

Giovanni
Aug 7 '08 #4
On Aug 7, 1:45 am, "Giovanni Dicanio" <gdicanio@_NOSPAM_email_DOT_it>
wrote:
<cron...@gmail.comha scritto nel messaggionews:d6********************************** @t1g2000pra.googlegroups.com...
I have code like this (pseudocode):
MyClass::MyClass()
{
Array1 = new D3DXVECTOR3[MaxVertexCount];
Array2 = new USHORT[MaxIndexCount];

Correct me if I'm wrong, but I think that Array1 and Array2 are defined like
this:

<code>

class MyClass
{
...

D3DXVECTOR3 * Array1;
USHORT * Array2;
...

};

</code>

In that case, the answer to your question is "no": your code is not
exception safe, if an exception is thrown in the constructor, Array1 and
Array2 are leaked.

As Carl already wrote, I think the best approach is to use std::vector
instead of new[] (and delete[]).

e.g.

<code>

#include <vector// Use std::vector

class MyClass
{
....

std::vector< D3DXVECTOR3 Array1;
std::vector< USHORT Array2;

...
};
The issue is that this is a managed ref class, so I cannot have that.
I can only have pointers to native types. Having:

std::vector< D3DXVECTOR3 >* Array1;

would still require me to allocate the vector with new.

Aug 7 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Gonçalo Rodrigues | last post by:
Hi, For error processing I found convenient maintaining a dictionary where the keys are exception *classes* and the values are callables. Of course, for this to work, exception classes have to...
6
by: Fred Zwarts | last post by:
Hello, I am trying to debug some complex debug code. In order to track the use of dynamically allocated memory, I replaced the standard global new and delete operators. (Not for changing the...
12
by: Bret Pehrson | last post by:
Suppose the following: // Unmanaged code class UnmanagedException /* not visible outside of unmanaged code */ { }; void DoSomething() /* visible (exported) to managed code */ { throw new...
10
by: tony | last post by:
Hello!! As you know every user defined exception must be derived from class Exception. Now to my question if I write catch then every exception will be caught. If I instead write...
3
by: JohnDeHope3 | last post by:
First let me say that I understand that Asp.Net wraps my exception in an HttpUnhandledException. I have found a lot of discussion about that on the web, which was informative, but not helpful. Let...
5
by: Bry | last post by:
I've created a class that offers an enhanced way of handling fatal exceptions. The class allows the user to optionaly submit a http based anonymous error report to myself, and also records details...
132
by: Zorro | last post by:
The simplicity of stack unraveling of C++ is not without defective consequences. The following article points to C++ examples showing the defects. An engineer aware of defects can avoid...
5
by: Vijay | last post by:
Hi All, I am not able to figure out what exactly happening in below code. what is control flow. Can anyone clear my confusion? Code: class A { public: A(){cout<<"In Constructor\n";}
2
by: Bob Altman | last post by:
Hi all, We have a native class modeled after the System::Exception class, and all exceptions that we throw derive from this class. For now this class is quite simple: just Description and...
9
by: =?Utf-8?B?UmFq?= | last post by:
How do I know which methods will throw exception when I am using FCL or other third party .Net library? I am developer of mostly native Windows applications and now .Net. After working few...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.