+ Reply to Thread
Results 1 to 2 of 2

Thread: Destructor is not being called in C++! What could be the reason?

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

    Destructor is not being called in C++! What could be the reason?

    Hi,

    I have following code and ~CXYZ() is not being executed!

    Compiler says: "deletion of pointer to incomplete type 'CXYZ'; no destructor called"

    Code:
    class CXYZ ;
    
    void Destroy(CXYZ *p)
    {
    	if (p) //if something
    	{
    		delete p;
    	}
    }
    
    class CXYZ
    {
    public:
    	CXYZ()
    	{
    	}
    
    	~CXYZ()
    	{
    	}
    };
    
    int main()
    {
    	CXYZ *p = new CXYZ();
    	Destroy(p);
    	return 0;
    }
    Destructor is not being called in C++! What could be the reason?

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

    This is case of partial defined type.

    Use following technique provided by boost::checked_delete.

    Code:
    #include <boost/checked_delete.hpp>
    
    class CDeleteMe ;
    
    void DeleteUndefinedObject(CDeleteMe *pDeleteMe)
    {
    	//PART 1 - delete
    	delete pDeleteMe ;
    
    	//PART 2 - checked_delete
    	//boost::checked_delete(pDeleteMe) ;
    }
    
    class CDeleteMe
    {
    public:
    	CDeleteMe()
    	{
    	}
    
    	~CDeleteMe()
    	{
    		printf("~CDeleteMe") ;
    	}
    } ;
    
    void UseDelete()
    {
    	CDeleteMe *pDeleteMe = new CDeleteMe() ;
    
    	//With PART 1 - delete uncommented and PART 2 commented, program will not execute "~CDeleteMe()" destructor.
    	//We may get warning based on the compiler we use.
    
    	//With PART 2 - checked_delete uncommented and PART 1 commented, program will execute "~CDeleteMe()" destructor!
    	DeleteUndefinedObject(pDeleteMe) ;
    }
    Note:
    Have a look at http://www.boost.org/doc/libs/1_48_0...ed_delete.html for more information.

    Thanks.

+ Reply to Thread

Tags for this 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