In the below code, author points that new operator
function call might cause an exception so that this implementation is not exception safe because object state is already changed in the first line.
String &String::operator =( const char *str ) {
// state is changed
delete [] s_;
if( !str ) str = "";
// exception might occur because of new operator
s_ = strcpy( new char[ strlen(str)+1 ], str );
return *this;
}
While reading, I wondered that do C library functions throw exception in C++ ? I know that there is no exception in C but since we are using C++ compiler, there might be exceptions.
So, can we consider c standard lib functions as exception safe function calls ?
Thank you.
Btw, for the record, right way (exception safe) to implement above function is below.
String &String::operator =( const char *str ) {
if( !str ) str = "";
char *tmp = strcpy( new char[ strlen(str)+1 ], str );
delete [] s_;
s_ = tmp;
return *this;
}