c++exceptionexception-safetyexception-safec-standard-library

Do C standard library functions which are included in C++ throw exception?


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;
}

Solution

  • Generally speaking, the C++ standard does not modify any of the functions from the C standard, except to decree the identifiers should refer to actual functions rather than macros. Thus, functions from the C standard library cannot throw an exception in any circumstance there the C standard decrees what a function can do.

    Loopholes that would allow exceptions include things like undefined behavior or callbacks (e.g. passing a comparator to qsort that throws an exception... although I'm not actually sure if that's allowed by the C++ standard). I don't think it particularly likely that library providers would spend any effort trying to add a feature of throwing exceptions in situations where there is undefined behavior.