1

So I have a union type struct that contains a pointer to a string as one of the types the union can hold and I want to overload the = operator so I can do assignments. In order to ensure that I do not have a memory leak I am checking to see if the type of the union is already a string, if it is I delete the old value and assign the new value.

My issue is that if i do "aString = aString" my check deletes the string that it means to assign and this causes a segfault of course. I know that this is not something that I would ever need to use but I just want to ensure that this case is handled properly. So my question is how can I handle this properly?

Young_Torso
  • 141
  • 1
  • 10

1 Answers1

1

To prevent self assignment, you have to make sure the source object is not the same as the target.

That’s why the assignment operators usually look like this:

person& person::operator=(const person& rhs)
{
    if (this != &rhs)
    {
        // free the old resources
        // and copy from rhs
    }
    return *this;
}

The move assignment operator should also perform this test (Move assignment operator and `if (this != &rhs)`).

Sometimes it could be usefull to change the assignment operator to take an object by value, not reference, so you do not need to check for self assignment and use the temporary object to move from or swap.

Mihayl
  • 3,821
  • 2
  • 13
  • 32