Search code examples
c++stdstringresource-cleanupexception-safety

Does std::string class handle clean up if the assignment operator fails due to length_error or bad_alloc?


Does std::string class handle clean up if the assignment operator fails due to length_error or bad_alloc? Does it give me back my intact string I provided?

UPDATE: SOLVED: YES OPERATOR= IS SAFE PER MY REQUIREMENTS. THE CODE BELOW ADDS NO VALUE TO EXCEPTION SAFETY

given this reference from https://cplusplus.com/reference/string/string/operator=/ about exceptions

if the resulting string length would exceed the max_size, a length_error exception is thrown. A bad_alloc exception is thrown if the function needs to allocate storage and fails.

The explanation below is assuming std::string class doesn't fix any assignment that was done.

I figured if I assigned *this ("num" below) to a temp I could save any damage done to *this if the line num = other.num; below failed. The reason I am not sure if this is futile is because this snippet num = temp;, The fact I do not check this for success could be a failure. Is my code futile? Is there a standard way to handle this that I am missing?

const BigInt 
&BigInt::operator=(const BigInt &other) 
{   
    string temp = num;                          // using string operator=
    if (temp.compare(num) == 0)
    {
        try 
        {
            num = other.num;
        }
        catch(...)
        {   
            num = temp;
            throw;
        }
        return *this;
    }
    return *this;
}

RESOURCES PER ANSWERS GIVEN:

  1. string operator= https://en.cppreference.com/w/cpp/string/basic_string/operator%3D

    > If an exception is thrown for any reason, this function has no effect (strong exception guarantee).   (since C++11)
    
  2. RAII Model https://en.cppreference.com/w/cpp/language/raii


Solution

  • Since C++11 it leaves the string intact.

    If an exception is thrown for any reason, this function has no effect (strong exception guarantee). (since C++11)

    cppreference