删除类对象的转换函数
Conversion function to delete class object?
是否可以为返回指针的类编写转换函数,并且也可以通过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"
相关文章:
- 转换函数,将 std::数组的双精度作为参数或双精度作为参数单独转换
- C++:用户定义的显式类型转换函数错误
- 为什么下面带有非常量转换函数的代码没有歧义?
- 为什么转换函数声明不需要至少一个定义类型说明符
- PCL:当我在setConditionFunction中使用std::bind 时,没有合适的转换函数
- C++ 通过自定义赋值运算符隐式转换函数参数
- 当我使用 void 函数的返回值(通过强制转换函数指针)时,究竟会发生什么?
- 在C++中自动向下转换函数参数
- static_cast:转换函数模板——它们真的有效吗
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类
- 隐式转换函数的返回对象时是否会影响性能?
- C++不存在合适的转换函数
- 为什么允许 int 和 const int 使用不同的转换函数?
- 使用转换函数直接初始化
- 为什么用户定义的转换函数模板不能有推导的返回类型?
- 为什么我会收到转换函数错误
- 选择用于赋值初始化的转换函数的优先级
- 我收到错误:没有合适的转换函数从 std::basic_istream<char、std::char_traits<char>> 到 char 存在
- 具有转换函数的 lambda,指向具有 C++ 链接的函数的指针
- 使用模板和部分专用化生成类型转换函数