【发布时间】:2019-10-16 14:58:39
【问题描述】:
C++ 对放置新和放置删除是不对称的。我们被允许以几乎任意的方式重载placement new。但是,放置删除函数仅从放置新表达式中调用。特别是,如果对象的构造函数抛出异常,则调用它们。根本无法为应用程序代码调用放置删除。
我有以下困惑和问题需要澄清:
1) 如果没有定义放置删除对应项,为什么 C++ 编译器不能简单地拒绝放置新方法签名?这样做可以帮助消除在这种情况下内存泄漏的可能性。
2) 如果我有多个内存池(由应用程序代码管理)并且我想要不同的位置 new 来从不同的池中分配内存,则根本无法支持这一点,因为无法知道哪个内存池指针来自运算符删除? (操作员删除只有 void* 信息)。有什么方法可以在 C++ 中实现这一点吗?
struct Node {
void* operator new(size_t size, Strategy s) {
// Depend on different strategy, allocate memory
// from different Memory pool
}
void operator delete(void* memory, Strategy s) {
// Return the memory to different Memory pool
// depends on the Strategy
// However this delete will only be invoked by
// c++ runtime if Node constructor throws.
}
void operator delete(void* memory, size_t s) {
// This delete doesn't have any clue about the
// the strategy. Hence, it can't decide which
// Memory pool to return to.
}
}
3) 在placement new 的上下文中,C++ 运行时将使用相同的参数调用placement delete。 C++ 运行时如何做到这一点?
【问题讨论】:
-
你可以使用“智能指针”吗?
-
您的评论无关紧要。
-
如果你在做
T* p = new (memory) T();,你不应该在做p->~T();吗?什么是“展示位置delete”? -
你不需要placement new:它只是调用析构函数,你可以直接这样做。因此,没有理由调用它。等等,您是否覆盖放置新行为?这甚至允许吗?这绝对不是一个好主意...
-
@MooingDuck
new调用的分配函数是可替换的,因此用户可以控制分配(和/或调试)
标签: c++ memory-management dynamic-memory-allocation delete-operator placement-new