+ Reply to Thread
Results 1 to 2 of 2

Thread: Is it OK to delete 'this' in C++?

  1. #1
    Junior Member
    Join Date
    Feb 2012
    Posts
    48

    Is it OK to delete 'this' in C++?

    Hi All,

    Is it OK to delete 'this' in C++?

    Regards.

  2. #2
    Senior Member
    Join Date
    Feb 2012
    Posts
    109
    Hi,

    It is OK to delete the 'this' pointer within class with one condition.

    You should not use the object object you call "delete this" statement.

    Following is the example:

    Code:
    class CStudent
    {
    private:
    	int m_nRoleID ;
    public:
    
    	CStudent(int nRoleID)
    	{
    		m_nRoleID = nRoleID ;
    	}
    
    	int GetRoleID()
    	{
    		return m_nRoleID ;
    	}
    
    	void DeleteMe()
    	{
    		delete this ;
    	}
    } ;
    
    void UseDeleteThis()
    {
    	/*
    	//This is undefined!
    	CStudent objStudent(1) ;
    
    	int nRoleID = objStudent.GetRoleID() ;
    
    	objStudent.DeleteMe() ;
    
    	nRoleID = objStudent.GetRoleID() ;
    	*/
    
    	CStudent *pStudent = new CStudent(1) ;
    
    	int nRoleID = pStudent->GetRoleID() ;
    
    	//It is OK to delete this!
    	pStudent->DeleteMe() ;
    
    	//undefined behaviour!
    	nRoleID = pStudent->GetRoleID() ;
    }
    Note:
    Object created on stack has undefined behavior.

    Regards.

+ Reply to Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts