删除类对象的转换函数

Conversion function to delete class object?

本文关键字:转换 函数 对象 删除      更新时间:2023-10-16

是否可以为返回指针的类编写转换函数,并且也可以通过delete表达式来删除我的对象?如果有,我该怎么做呢?

要使delete X生效,X必须是原始对象的类型(或带虚析构函数的共享基类型)。因此,通常不需要这样的操作符,因为只有在隐式强制转换为基型时才会起作用,而基型不需要转换操作符。

对于其他任何事情,答案都是"不"。

class Base
{
public:
  virtual ~Base() {}
};
class Thing1 : public Base
{
public:
  ... whatever ...
}
class Thing2 : public Base
{
public:
  ...
}

你可以做的事情:

Thing1 * t = new Thing1;
Base * b = t; // okay
delete b;  // okay, deletes b (which is also t)
           // BECAUSE we provided a virtual dtor in Base,
           // otherwise a form of slicing/memory loss/bad stuff would occur here;
Thing2 * t2 = new Thing2;
Thing1 * t1 = t2; // error: won't compile (a t2 is not a t1)
                  // and even if we cast this into existence, 
                  // or created an operator that provided this
                  // it would be "undefined behavior" - 
                  // not "can be deleted by delete operator"