protected destructor with unique_ptr

前端 未结 2 1662
抹茶落季
抹茶落季 2020-12-12 04:28

I am trying to call APIs from a third party library.

There is a trouble when I want to use unique_ptr with a class having protected destructor.

Here is the e

2条回答
  •  暖寄归人
    2020-12-12 04:53

    Unfortunately, the real way to get rid of this issue is to not derive classes from Parent, and to not manage the lifetime of Parent objects (or any derived classes) using std::unique_ptr.

    In other words, you need to redesign your classes.

    The reasons I say this are

    • If someone has gone to the trouble of giving Parent a protected non-virtual destructor, the intent is most likely to avoid having a Parent * which actually points at an instance of a derived class and is released using operator delete. A library designer will not (normally) do this without good reason.
    • Your code can be forced to compile as is (e.g. by making std::default_delete a friend of Parent). However, std::default_delete is used by unique_ptr to release the managed object. And it uses operator delete. That gives undefined behaviour if the object being managed by the unique_ptr is of a type derived from Parent.

    So, in short, you're working around the intent of (whoever designed) your third party library and, if you force the code to compile anyway, your reward will be undefined behaviour.

提交回复
热议问题