0

How do you properly use the "delete" keyword?

So there are different classes just for it, and bla bla bla. But how exactly can i use the delete keyword for something? And why do destructors have to be in it? This is the easiest question, but I'm too stupid :( thank you!

28th Jul 2018, 3:41 AM
Coder333
3 Answers
+ 1
delete must calls destructors to do the work that we should do before we recycle the memory. How to use delete? very easy, use it after you've used new and you donā€™t want to use the object you allocated anymore. this maybe help https://en.cppreference.com/w/cpp/language/delete And if you you're interested in it, you can also learn something about allocator.
28th Jul 2018, 6:29 AM
Constructor
Constructor - avatar
+ 1
After c++ program finishes, only memory in so called stack is freed. If you create an object in stack MyClass obj; then you don't have and can not use delete delete obj; will lead to an error. But if you create a pointer or reference and assign a new object to it MyClass*p = new MyClass; only a pointer *p to MyClass object is created in the stack and is destroyed after the program terminates. The actual object of MyClass is created in the region of memory called heap, which is, actually, the rest of computer RAM, except for the stack. And it is not destroyed, but all pointers to it are lost, so we have a chunk of memory, filled with garbage. That's called memory leak. To prevent it, you should deallocate the memory, you've allocated to the pointer by doing delete p;
28th Jul 2018, 6:38 AM
Š”Š¼ŠøтрŠ¾ Š†Š²Š°Š½Š¾Š²
Š”Š¼ŠøтрŠ¾ Š†Š²Š°Š½Š¾Š² - avatar
0
You do not actually have to specify a destructor for every class. If you don't, calling delete p; will free the memory, which was allocated to the object on it's creation. But there could be a problem. An object can contain in itself pointers and references and when an object is destroyed, only those pointers will be destroyed, and objects, assigned to them will not. Class SomeClass { public: OtherClass*oc; MyClass() { oc=new OtherClass; } }; When we do SomeClass *p = new SomeClass; inside object of SomeClass, assigned to pointer *p an object of OtherClass, assigned to pointer *oc will be created. If we do delete p; then only *oc pointer will be destroyed, but an object it point to will remain in memory. To prevent it, we need to make a destructor for SomeClass ~SomeClass() { delete oc; } Also class can own some resources, files, network or database connections, etc. which should be freed on destroying the class - this is also a job for a destructor.
28th Jul 2018, 6:53 AM
Š”Š¼ŠøтрŠ¾ Š†Š²Š°Š½Š¾Š²
Š”Š¼ŠøтрŠ¾ Š†Š²Š°Š½Š¾Š² - avatar