0

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

FredFrugal
  • 75
  • 1
  • 10
  • 1
    Standard library types are designed with RAII in mind. They will not leak memory or anything like that if an exception is thrown. They also try their best to give strong exception guarantees, such that a failed operation will leave objects in their previous state, as far as is possible. – user17732522 Oct 22 '22 at 11:41

1 Answers1

1

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

Daniel
  • 30,896
  • 18
  • 85
  • 139
  • I'd have to dig into the standards further to verify, but my understanding is that, before C++11, `basic_string` (like other standard containers) offered [at least] a weak exception guarantee - essentially, if an exception is thrown, the object may be safely destructed. – Peter Oct 22 '22 at 12:36