473,396 Members | 2,024 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,396 software developers and data experts.

C++ Exception: Why does this program behave differently for pointer and array of pointer

Hi,
can somebody please help me figure out what is wrong with the
following program? If I run this program, then the destructor for the
first pointer in the array is called because exception occurs as soon
as it tries to allocate the second pointer in the array but the
destructor for the pointers a1 and a2 are not called.

Does any one have answers ?
Thanks in advance,
Divick

#include <exception>
#include <iostream>
using namespace std;

class A
{
static int count;
int id;
public:
A() throw(int)
{
id = count;
count++;
cout << "Inside A's constructor object id " << is->>id <<
endl;
if(id==3)
throw 0;
}
virtual ~A()
{
cout << "Inside A's destructor for object id " <<
this->>id << endl;
}
};
int A::count = 0;
int main(){
try{
A * a1 = new A();
A * a2 = new A();
A * array = new A[3];
cout < < "Exiting try" << endl;
}catch(...){
cout << "Inside catch..." << endl;
}
}

Sep 11 '05 #1
7 1347
Divick wrote:
Hi,
can somebody please help me figure out what is wrong with the
following program? If I run this program, then the destructor for the
first pointer in the array is called because exception occurs as soon
as it tries to allocate the second pointer in the array but the
destructor for the pointers a1 and a2 are not called.

Does any one have answers ?


OK you are under a serious misapprehension about C++. There are no
destructors for pointers in C++. Simple as that. This one thing that
what makes pointers so difficult to handle correctly.

When an exception is thrown in a constructor, then if the constructor
was being used in a new operator then the memory for that operation will
be freed (because there would be no other way to free it), but any other
allocated memory is your responsibility to free.

john
Sep 11 '05 #2
Ian
Divick wrote:
Hi,
can somebody please help me figure out what is wrong with the
following program? If I run this program, then the destructor for the
first pointer in the array is called because exception occurs as soon
as it tries to allocate the second pointer in the array but the
destructor for the pointers a1 and a2 are not called.

Does any one have answers ?


Dynamic objects don't get destroyed when they go out of scope, you have
to use delete. You see the first element in the array (which is an A,
not a pointer to A) being destroyed.

Ian

PS, you don't have to type this->.
Sep 11 '05 #3
Hi John,
thanks for you prompt reply. Yes I understand that there
is no constructor/destructor for pointers in C++ actually what I meant
was constructor of the class to whose' instance this pointer points (
didn't write so explicitly to avoid confusion and it was implicit).
Regarding your answer, do you mean that in the creation of
A * array = new A[3];
the new is implicitly called by the operator [], which allocates three
instances of class A and hence the destructor will also be called for
it, while in case of simple pointer allocation A * a = new A(); since
new is called by me and hence I will need to delete ?

Thanks,
Divick

Sep 11 '05 #4
Divick wrote:
Hi John,
thanks for you prompt reply. Yes I understand that there
is no constructor/destructor for pointers in C++ actually what I meant
was constructor of the class to whose' instance this pointer points (
didn't write so explicitly to avoid confusion and it was implicit).
Regarding your answer, do you mean that in the creation of
A * array = new A[3];
the new is implicitly called by the operator [], which allocates three
instances of class A and hence the destructor will also be called for
it, while in case of simple pointer allocation A * a = new A(); since
new is called by me and hence I will need to delete ?
No I didn't mean that. In both cases you must explicitly call delete
(actually you must call delete[] for the first case).

However your original question was actually about what happens when a
constructor throws an exception. Ian pointed out the correct answer (I
think he understood exactly what you were asking a bit better than me).

If you write

A* a = new A[3];

then the constructor for A will be called three times (normally). If the
second call to the constructor throws an exception then (a) the third
constructor call won't happen, and (b) the destructor for the first
constructed object will be called, (c) the memory allocated by new will
be freed.

This should be exactly what you want to happen, because it means you
don't have to do any cleanup yourself. All the objects that were
cnostructed have been destroyed, and all the memory that was allocated
has been freed.

john

Thanks,
Divick

Sep 11 '05 #5

Maybe your fundamental misunderstanding is that

A* a = new A[3];

is *not* an array of pointers. (Sorry I didn't read the full subject of
your post).

This is an array of pointers

A** a = new A*[3];

Try that, and see what behaviour you get.

john
Sep 11 '05 #6
Thanks for the answer. I use this-> to make it more explicit (probably
a good programming practise). :)

Divick

Sep 12 '05 #7
John, Ian thanks for your answers. Similar answers from several people
in lang.c++.moderated list. See my post on moderated list with the same
title.

Thanks

Sep 12 '05 #8

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

Similar topics

1
by: Srinadh | last post by:
Hi all, We have files with about 20 to 30 fields per row. We are trying to update such files with about 60 rows as contiguous data in a CLOB field. It passes through. But when we try...
24
by: David Mathog | last post by:
If this: int i,sum; int *array; for(sum=0, i=0; i<len; i++){ sum += array; } is converted to this (never mind why for the moment):
11
by: chopsnsauce | last post by:
Here's the example: Dim frm As New FORM1 Try frm.show Catch ex As Exception msgbox ex.message
10
by: puzzlecracker | last post by:
It shouldnt, since reference object is destroyed in the stack frame.
89
by: Cuthbert | last post by:
After compiling the source code with gcc v.4.1.1, I got a warning message: "/tmp/ccixzSIL.o: In function 'main';ex.c: (.text+0x9a): warning: the 'gets' function is dangerous and should not be...
42
by: Sheldon | last post by:
Hi, This program works when tested with gdb ( see results 1) but when used in a larger program where 12 becomes 1500 there exists a problem when freeing the memory ( see results 2). Can anyone...
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...
13
by: Randy Graham | last post by:
While reviewing someone else's c++ code recently I was horrified to find something like this: (example only) A. char a; memset(&a, 0, 10); memcy(&a, "hello", 6);
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: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
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
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.