Re: Composite object and exception Handling
Pallav singh <singh.pallav@gmail.com> wrote in news:a0c4ce87-b32a-46a8-
ad4d-2763d06b4f2c@r21g2000pri.googlegroups.com:
Hi All,
i am new to C++.
in the given example , for given composite object if part of composite
object fails , compiler call destructor for
parts of composite objects for which constructor was called
successfully.
Since exception is the way for constructor to tell that they have
failed, but there we do not specify any unique Id to distinguish which
sub part of composite object has got failed.
The compiler knows perfectly well which subobjects it has already
constructed, and will destruct them properly if an exception occurs
before the most derived object construction is completed. In principle it
may use some kind of ID-s to keep the track (probably not), but this is
strictly an implementation detail which should not concern the
programmer.
In your code you have to just stick to a sane design and it will
automatically ensure correct behavior in case of exceptions. The simplest
rule to achieve this is that each class ought to manage only one resource
(like a dynamically allocated int array), which is acquired in the
constructor and released in the destructor. In that case one should not
need any catch blocks at all.
Is it something specified in Language reference manual of C++ , how
compiler need to implement them.
++++++++++++++++++++++++++++++++++++++++++++++++++
#include <iostream>
using namespace std;
class B
{
public :
int * ptr;
All data, especially pointers, should be private.
B()
{
try
{ ptr = new int(4); }
You probably meant int[4]?
catch(...)
{ delete []ptr; }
As written this snippet is quite buggy: if the 'new' operator throws, the
ptr variable is uninitialised and calling delete on it is neither needed
nor allowed. Moreover, the catch(...) block eats the exception so C++
thinks the object is constructed successfully, and will call the
destructor eventually, which will try to delete ptr again - another bug.
cout <<" Constructor of B Called "<< endl;
}
~B()
{
delete []ptr;
hth
Paavo