5 ms·
But is it as evil as? delete this; https://isocpp.org/wiki/faq/freestore-mgmt#delete-this https://isocpp.org/wiki/faq/freestore-mgmt#delete-this
by 1letterunixname 3y ago
But is it as evil as?
delete this;
https://isocpp.org/wiki/faq/freestore-mgmt#delete-this https://isocpp.org/wiki/faq/freestore-mgmt#delete-this
- spacechild1 3y agoIt certainly has its use cases, e.g. classes with intrusive reference count, where the "release" method would destroy the object once the refcount has reached 0.
- amluto 3y agoIs that really a good use case? Suppose you have: struct foo { atomic<int> refcount; // other stuff }; You can pass around a pointer, COM-style, and call ->Release as needed. But you can be a lot less error-prone by passing around a smart pointer that understands the intrusive refcount and handles releasing. At which point you get something like 'delete ptr' in a destructor, not 'delete this' in a Release function.
- spacechild1 3y agoIn practice, people would (hopefully) wrap the whole thing in a smart pointer anyway, instead of manually calling addRef() and release(). But for COM style interfaces you need the release() method because you only want to expose pure virtual interfaces.
- Const-me 3y ago> 'delete ptr' in a destructor, not 'delete this' in a Release function That approach requires client and server to be written in the same language, use the same memory allocator, and same compiler. For COM objects, often all of these are false. For example, C#, PowerShell or VBScript code can call IUnknown.Release() method of C++ implemented COM objects, which will cause C++ code to deallocate the memory. However, these higher level languages can’t directly delete C++ objects: they know nothing about C++ runtime, or C runtime.
- wheybags 3y agoI'm a big fan of: this->~MyClass(); new (this) MyClass(); I have unironically used this
- amluto 3y agoIn a language with affine types (i.e. real move semantics, like Rust but not like C++), destroying this is safe. OTOH deleting, as in freeing memory under the assumption that it was allocated in a particular manner, is only safe if you can somehow enforce that it was allocated that way.
- mgaunard 3y agowhich you can by making the constructor private.