Explain pointer use

I'm reading Coding Interview by Harry He
Then suddenly this code bugged me so bad...

1
2
3
4
5
6
7
8
9
CMyString& CMyString::operator =(const CMyString &str) { 
   if(this != &str) { 
      CMyString strTemp(str); 
      char* pTemp = strTemp.m_pData; 
      strTemp.m_pData = m_pData; 
      m_pData = pTemp; 
   } 
   return *this; 
}


Trouble :
m_pData = pTemp;

This code is as you can see an = operator overloading, take a string class as its parameter, then check difference between this and that string, create new string and swap between strTemp.m_pData and this.m_pData. So when the function returns, strTemp, pointing to current data is deleted, then this.m_pData is assigned new value from temporary. But since strTemp is deleted, would this.m_pData pointing to NULL ????

Nope. strTemp destructor will destroy old m_pData which was contained in *this and isn't needed now. Both *this and str will contain identical copies of m_pData if copy constructor was properly defined.
Last edited on
Topic archived. No new replies allowed.