为什么在C ++中没有放置删除表达式? [英] Why there is no placement delete expression in C++?

查看:115
本文介绍了为什么在C ++中没有放置删除表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么C ++没有直接对应于展示位置new的展示位置删除,即调用析构函数并调用适当的位置删除操作符?

Why C++ hasn't placement delete that directly corresponds to the placement new, i.e. calls the destructor and calls appropriate placement delete operator?

例如:

MyType *p = new(arena) MyType;
...
//current technique
p->~MyType();
operator delete(p, arena);

//proposed technique
delete(arena) p;


推荐答案

c $ c>在被动态分派的非成员或静态成员函数中是唯一的。具有虚拟析构函数的类型从最衍生的析构函数执行对它自己的 delete 的调用。

struct abc {
    virtual ~abc() = 0;
};

struct d : abc {
    operator delete() { std::cout << "goodbye\n"; }
};

int main() {
    abc *p = new d;
    delete p;
}

运行此示例。)

为了使用放置删除,析构函数必须以某种方式将附加参数传递给操作符删除

For this to work with placement delete, the destructor would have to somehow pass the additional arguments to operator delete.


  • 解决方案1:将参数传递给虚函数。这需要为每个静态成员和全局 operator delete 重载使用不同的参数创建单独的虚拟析构器。

  • 解决方案2: / strong>让虚拟析构函数返回一个指向调用者的函数指针,指定应该调用 operator delete 。但是如果析构函数查找,这会遇到需要多个虚函数定义作为#1的相同问题。

  • Solution 1: Pass the arguments through the virtual function. This requires a separate virtual destructor for every static member and global operator delete overload with different arguments.
  • Solution 2: Let the virtual destructor return a function pointer to the caller specifying what operator delete should be called. But if the destructor does lookup, this hits the same problem of requiring multiple virtual function definitions as #1. Some kind of abstract overload set would have to be created, which the caller would resolve.

你有一个完美的点,并且它将是一个很好的补充到语言。将其修改为 delete 的现有语义在理论上可能是可能的。但是大多数时候,我们不使用 delete 的完整功能,它足以使用一个伪析构函数调用,后面跟 arena。 release(p)

You have a perfectly good point, and it would be a nice addition to the language. Retrofitting it into the existing semantics of delete is probably even possible, in theory. But most of the time we don't use the full functionality of delete and it suffices to use a pseudo-destructor call followed by something like arena.release(p).

这篇关于为什么在C ++中没有放置删除表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆