我有一个使用placement new分配的对象。当不再需要该对象时,我显式地使用它的析构函数,然后自己处理内存,如网络上的各种资源中所述。
但是,我不清楚编译器是否可以为析构函数调用生成任何额外的“后台魔法”,而不仅仅是为析构函数内部的内容生成指令。实际的问题是:在“placement-new”的情况下,有什么会阻止我使用“自定义析构函数”而不是常规(〜语法)析构函数?简单的类方法,包含所有常用的析构函数代码,但可能额外接受参数。
这是一个例子:
class FooBar {
FooBar() { ... }
...
void myCustomDestructor(int withArguments) { ... }
...
};
int main() {
...
FooBar* obj = new (someAddress) FooBar();
...
obj->~FooBar(); // <- You're supposed to do this.
obj->myCustomDestructor(5); // <- But can you do this instead?
...
// Then do whatever with the memory at someAddress...
}
自定义析构函数有什么缺点吗?