More effective c++
Exception
void processAdoptions ( istream & dataSource )
{
while (dataSource ) {
ALA *pa = readALA ( dataSource ) ;
pa -> processAdoptions () ;
delete pa ;
}
}
# way to handle processAdoptions () function exception
1. try - catch
void processAdoptions ( istream & dataSource )
{
while ( dataSource ) {
ALA * pa = readALA (dataSource ) ;
try {
pa->processAdoptions () ;
}
catch(...){
delete pa;
throw ;
}
delete pa ;
}
}
2. using auto_ptr ( one of smart pointer )
void processAdoptions ( istream & dataSource )
{
while (dataSource ) {
auto_ptr <ALA> pa ( readALA ( dataSource ) ) ;
pa -> processAdoptions () ;
}
}
# resource leakage in contrutor
class BookEntry {
public :
BookEntry ( const string & name , const string & address = "" ,
const string & imageFileName = "", const string * audioClipFileName = "") ;
~BookEntry() ;
void addPhoneNumber( const PhoneNumber & number ) ;
private :
string theName ;
string theAddress ;
list<PhoneNumber> thePhone ;
Image * theImage ;
AudioClip * theAudioClip ;
} ;
- construction definition
BookEntry::BookEntry ( const string & name , const string & address = "" ,
const string & imageFileName = "", const string * audioClipFileName = "") :
theName ( name ) , theAddress(address) , theImage ( 0) , theAudioClip (0)
{
...
theImage = new Image ( imageFileName ) ;
theAudioClip= new AuioClip ( audioClipFileName ) ;
...
}
# fully constructed -> deconstructor
1. try {
...
theImage = new Image (imageFileName ) ;
..
theAudioClip= new AuioClip ( audioClipFileName ) ;
}
catch ( ...)
{
delete theImage ;
delete theAudioClip;
}
# if the pointer is constant ?
Image * const theImage ;
AudioCLip * cosnt theAudioClip
BookEntry::BookEntry ( const string & name , const string & address = "" ,
const string & imageFileName = "", const string * audioClipFileName = "") :
theName ( name ) , theAddress(address) , theImage ( initImage(imageFileName ) ) , theAudioClip (initAudioClip(audioclipFileName))
{ }
#for exception handling in destructdor
session::~session ()
{
try{ logDeestruction(this ) ;
}
catch(...) {}
}