Strictly speaking, in the release method, you can simply write delete this; . But here you have to be 100% sure that:
- The object was created using
new (not new[] , not placement new , it is not a local stack object, not a global object, not a class member) - The
release method will be called last. - Part of the
release method after the line delete this; does not operate on any object data. - No one will use
this in any way after delete this; (it is impossible to compare this with nullptr , with another pointer, perform type conversions)
If these requirements are met, then everything will work as it should. The release method will do exactly what is expected of it.
Although I would not write like that. First, because delete this; This is a dangerous and ugly design. Secondly, you "smear" the same type of functionality into two classes. myDevice deals with myDevice , while object destroys it. Not 100% sure, but it seems to me that the High Cohesion principle has been violated (let me be corrected if it is not)
Where this approach would be more logical:
IObject* object = myDevice->сreate(); //... myDevice->release(object);
Or this:
std::shared_ptr<IObject> object = myDevice->сreate();