placement delete用于在placement new中发生异常时释放内存。所以我做了一个测试:
#include <iostream>
#include <new>
using namespace std;
class A {
public:
    A(){
        cout << "constructor" << endl;
        throw 1;
    }
};
void* operator new(size_t size, int i){
    cout << "in placement new" << endl;
    return ::operator new(size);
}
void operator delete(void *ptr, int i){
    cout << "in placement delete" << endl;
    ::operator delete(ptr);
}
int main(){
    int o = 9;
    A* a = new(o) A;
}位置删除函数从来没有被调用过,它只是退出了。为什么?
发布于 2018-11-30 17:12:41
这是因为您没有捕捉到异常,所以不会调用用于删除的相关代码。只需将其封装在try/catch块中:
try 
{
    int o = 9;
    A* a = new(o) A;
} 
catch (int i) { }请记住,您必须有效地捕获构造函数引发的异常,而不仅仅是任何异常。
https://stackoverflow.com/questions/53554133
复制相似问题