0
是否可以为返回一个指针的类编写一个转换函数,哪个也可以被删除表达式用来删除我的对象?如果是这样,我该怎么做?转换函数删除类对象?
是否可以为返回一个指针的类编写一个转换函数,哪个也可以被删除表达式用来删除我的对象?如果是这样,我该怎么做?转换函数删除类对象?
要使X工作,X必须是原始对象的类型(或共享基类型w /虚拟析构函数)。所以通常情况下,你永远不需要这样的操作符,因为它只有在你进行隐式强制转换时才会有效,不需要转换操作符。
而对于其他任何答案都是有效的“否”。
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"
我假设你回来'this'?否则,这是不可能的。 – tenfour
你的意思是'class T {operator T *(){return this; }};'?但是,我很难想到这种情况是有用的或可取的。 –
没有意义。一个对象不能决定它是如何分配的,所以它不应该公开任何逻辑来以任何特定的方式释放它。 –