How to hide "delete" in class hierarchy?

So, I am moving from the “owned” object model to the “managed” object model in the project that I am doing. Currently to create a new Thing one

Thing *thing = new Thing();

and get rid of it and destroy its owner

delete thing

Now there is a lot of “delete thing”, and many of them are removed from the superclass of the Thing class, since the superclass has a virtual destructor.

Now in the managed model there is a base class with a virtual destructor that the manager will delete. The user must call "release" on it DO NOT delete.

Therefore, I would like to somehow reject the “delete thing” as a compile-time error during compilation. Creating a destructor is “protected”, it does not seem to work because of a virtual destructor based on it. And it should be at least protected for subclasses (I think).

Does anyone have any idea?

+3
source share
4 answers

You need the destructors to be protected both on your base and on your subclasses. Then it should work fine.

For example, the code below generates compile-time errors for strings delete.

class A
{
protected:
    virtual ~A() {}
};


class B : public A
{
protected:
    virtual ~B() {}
};

int main()
{
    B* b = new B;
    A* a = new B;

    delete b;
    delete a;

    return 0;
}
+6
source

Of course; override operator deletein your class and make it private:

struct Foo
{
private:
    void operator delete(void*); // no body (never called)
};
+2
source

. delete ? , / ( opeartor new operator delete). , , operator new operator delete (, ), , .

, (, ..) / , , . ( , ).

0
source

Good - yes, if I redefine the delete operator in the base class, if this leads to a failure of the deletion, however, it must be functional, because it is called when the virtual destructor is executed.

In my case, I also have to make sure that the basic interface “object” for the IUnknown equivalent in com has a protected destructor and constructor, because smart pointers implicitly cast to one of them, and this would be flawlessly passed to delete and compile !!! (and application crash too)

that's why I am

class ObjectInterface
protected:
     ~ObjectInterface();
public:
     virtual int method1() = 0;
...
};

class ObjectBase
     : public ObjectInterface
     , public ObjectImpl // has virtual destructor on it
{
protected:
    static void operator delete(void *p) { ::operator delete(p); }
public:
     int method1(); // default impl
};

class MyObject
    : public ObjectBase
{
protected:
    MyObject();
    ~MyObject();
public:
    static SharedPointer<MyObject> create() 
    { 
        return(SharedPointer<MyObject>(new MyObject()); 
    }
};

SharedPointer<MyObject> sp = MyObject::create();
MyObject *mo = sp;

sp = NULL; // fine does actual delete inside ObjectImpl

delete sp; // compile error
delete mo; // compile error
0
source

Source: https://habr.com/ru/post/1721733/


All Articles