Skip to main content
GameDev.net gamedev.net
🔒 Locked

Destructor VS delete

Started by wah_on_2 Apr 21, 2002 at 8:41 AM 4 replies 450+ views
Original Post
wah_on_2
wah_on_2
If i created a object dynamically, should i call the object destructor or delete the object directly? and why? e.g.
  
class aThing
{
public:
   aThing(....);
   virtual ~aThing();
   ................
}

void main()
aThing *p;
p = new aThing(....);
               //<----delete p;

               //<----p->~aThing();

               //which one is better?

}
  
Also, if the aThing class contains a data member that is a objectA. If i use delete p;, will the objectA deleted? Thanks
VolkerG
VolkerG
For an object created with new you must call delete. The destructor won''t free the memory the object uses on the heap.
Waverider
Waverider
The destructor is called just before the deletion takes place. It shouldn't be called directly.

If you have a data member in aThing that is a class, then when the delete for the aThing object is called, the data member will also be removed from memory, after the destructor for the data member is called.

[edited by - Waverider on April 21, 2002 10:06:02 AM]

[edited by - Waverider on April 21, 2002 10:07:23 AM]
It's not what you're taught, it's what you learn.
Arild Fines
Arild Fines
quote:
Original post by Waverider
It shouldn''t be called directly.


Unless you have been using placement new.



--AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.[Project site] [IRC channel] [Blog]
wah_on_2
wah_on_2
I clear now. Thank you.

what is placement new?
Martee
Martee
Placement new is the method by which you can specify the address that an object is allocated at. As Arild said, you must manually call the destructor in this case. Here's a quick example:

      
class SomeCoolClass
{
...
};


int main(int argc, char* argv[])
{
char* buffer = new char[sizeof(SomeCoolClass)];
SomeCoolClass* p = new (buffer) SomeCoolClass;

p->~SomeCoolClass();
delete[] buffer;

return 0;
}


[edited by - Martee on April 21, 2002 12:51:06 PM]
ReactOS - an Open-source operating system compatible with Windows NT apps and drivers

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.