Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide "delete" on a class hierarchy?

Tags:

c++

So I am migrating from an "owned" object model to a "managed" object model in a project I am doing. Currently to make a new Thing one does

Thing *thing = new Thing();

and to get rid of it and destroy it the owner does

delete thing

Now there are a lot of "delete thing"s out there and many of them are deleting from a superclass of Thing pointer because the superclass has a virtual destructor.

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

So I would like to somehow at compile time reject "delete thing" as a compile time error. Making the destructor "protected" doesn't seem to work because of the virtual destructor on the base. And it needs to be at least protected for subclasses (I think).

Anyone have any ideas?

like image 240
Peter Kennard Avatar asked Dec 20 '25 08:12

Peter Kennard


1 Answers

You need to make the destructors protected on both your base and your subclasses. It should work okay then.

For example the code below generates compile time errors for both delete lines.

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;
}
like image 180
Troubadour Avatar answered Dec 21 '25 23:12

Troubadour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!