In the fallowing assignment operator I'm deleting a dynamically allocated data member of the Class I'm in. I accidentally left the "delete" in when turning the code in, but it still seems to work completely fine. What exactly is happening when I call delete and how is the swap function still working if I'm deleting m_itemArray before assigning it to temp in the Swap function?
Assignment operator:
Set& Set::operator=(const Set& rhs)
{
if (this != &rhs)
{
delete[] m_itemArray;
Set temp(rhs);
swap(temp);
}
return *this;
}
Swap Function:
void Set::swap(Set& other)
{
ItemType * temp = m_itemArray;
m_itemArray = other.m_itemArray;
other.m_itemArray = temp;
}
The way I'm thinking it works right now, is I'm letting the computer access the memory m_itemArray is using, but I'm getting lucky because the computer is not editing whatever is stored in that memory space by the time I'm accessing the Swap function.
Your hypothesis is almost certainly correct. Except in very high security systems or when using debugging harnesses, there is no reason to rewrite the memory that has been released (which is what happens with the delete operation).
Actually, even the release itself might not occur immediately but rather be performed at a more convenient time (this operation can grow in complexity and become what is called a garbage collector, which in turn can render the use of explicit releases unnecessary - but the topic gets complicated).
So, until that moment, the memory is still reachable and may be used. Even afterwards, there is a possibility that the value is not reused and overwritten, and is still viable (which may contribute to hiding what is actually a dangerous bug). Of course, you have no guarantees, and trying to access freed memory can lead to all sorts of troubles.
To catch this kind of errors, with some systems you could link your executable with a different memory manager or library that will overwrite the soon-to-be-released memory with either random or telltale values before actually releasing it. With older systems that had no real hardware protection support, e.g. MS-DOS, this was the only check possible, and it remained a popular choice for quite some time (I remember electricfence, for example).