转换函数删除类对象?

时间:2011-11-21 00:23:16

标签: c++

是否可以为返回指针的类编写转换函数,delete表达式也可以使用它来删除我的对象?如果是的话,我该怎么做?

1 个答案:

答案 0 :(得分:1)

要使删除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"