The program creates an object

IObject* object = myDevice->CreateObject(); //IObject абстрактный класс 

I want to destroy an object like this object-Release(); instead of myDevice->RemoveObject();

Is it correct that each variable in a descendant class should be a pointer and that when designing you need to allocate memory manually and when you call the Release () function you just need to manually release it?

  • 2
    Both ways are wrong. Read better about smart pointers. - Pavel Mayorov
  • I assume the COM methodology is used. Release reduces the reference count and destroys the object if it reaches 0. - Unick
  • In general, the question does not make it clear that you are using? Com? Or samopisny similarity COM? - Sublihim
  • only the function name is taken from COM - user185136

1 answer 1

Strictly speaking, in the release method, you can simply write delete this; . But here you have to be 100% sure that:

  1. 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)
  2. The release method will be called last.
  3. Part of the release method after the line delete this; does not operate on any object data.
  4. 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(); 
  • one
    std::shared_ptr . - αλεχολυτ
  • @alexolut, exactly, thanks. I'm used to qt-names :) - yrHeTaTeJlb