3 ms·
Well I guess it's a good thing no one ever had a double free in C :) > They mean you can never tell what `delete` does. Can you elaborate on this? A destructo
by moshegramovsky 4y ago
Well I guess it's a good thing no one ever had a double free in C :)
> They mean you can never tell what `delete` does.
Can you elaborate on this? A destructor is a function that's built into an object. It's really not more complicated than that. If malloc/free are functions that should be used in pairs, then the constructor/destructor pair tries to provide a convenient and structured way to know where malloc/free go. You would call new in the constructor and delete in the destructor.
I'm curious to know what you prefer?
- stevenhuang 4y agoCases can arise where ownership of objects are not clear (which is a separate issue) but when they do occur, you can have a custom destructor that frees a lot of other objects, and then these other objects may in fact be "owned" elsewhere. Somewhere down the line these other objects are freed again, causing double free.
- adrianN 4y agoHow would malloc/free be better in that situation?
- ihatepython 4y agoI don't know, but when I use C, I like to statically allocate everything if at all possible, I don't free() anything, I let the OS clean everything up at exit(). A lot of the small Unix utilities don't necessarily need dynamic memory allocation IMO
- adrianN 4y agoThat's a good strategy in C++ too. Check the MISRA guidelines for example.
- stevenhuang 4y agoI'm not saying it's better, it wouldn't. Parent was asking in what scenarios can custom destructor causes issue so I just provided one.
- torstenvl 4y agomalloc/free are better because free(window) could never call free(window->widget->font)
- scaredginger 4y agoThis sounds much more like a case of awful design than destructors being problematic
- stevenhuang 4y agoCan't argue with that.