删除与析构函数的显式调用

delete vs explicit call of destructor

本文关键字:调用 析构函数 删除      更新时间:2023-10-16

在 c++ 中,调用 delete 分配了 new 的对象调用类的析构函数,并释放内存。如果不删除对象,而是显式调用其析构函数,然后释放内存,会有什么区别吗?

例如,考虑以下示例。

#include <iostream>
struct A {
  int i;
  ~A() { std::cout << "Destructor, i was " << i << std::endl; }
};
int main()
{
  A* p = new A{3};
  p->~A();
  free(p);
  return 0;
}

使用 g++ 7.3.0 和 clang 6.0.1 以及 -Wextra -Wall -pedantic 编译代码不会引发任何警告。正如预期的那样,程序的输出是

Destructor, i was 3

使用 valgrind/memcheck 运行程序会给出不匹配的 free/delete 错误:

==27743== Memcheck, a memory error detector
==27743== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==27743== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info
==27743== Command: ./destructor
==27743== 
Destructor, i was 3
==27743== Mismatched free() / delete / delete []
==27743==    at 0x4C3033B: free (vg_replace_malloc.c:530)
==27743==    by 0x4009FC: main (in /tmp/destructor)
==27743==  Address 0x5bbac80 is 0 bytes inside a block of size 4 alloc'd
==27743==    at 0x4C2F77F: operator new(unsigned long) (vg_replace_malloc.c:334)
==27743==    by 0x4009DA: main (in /tmp/destructor)
==27743== 
==27743== 
==27743== HEAP SUMMARY:
==27743==     in use at exit: 0 bytes in 0 blocks
==27743==   total heap usage: 3 allocs, 3 frees, 73,732 bytes allocated
==27743== 
==27743== All heap blocks were freed -- no leaks are possible
==27743== 
==27743== For counts of detected and suppressed errors, rerun with: -v
==27743== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

但是,没有内存泄漏。

我当然知道,处理上面代码中p的对象的标准方法是调用delete。我的问题更正式:

  • delete完全等效于对析构函数的调用和 free ?标准是否指定了这一点,或者我遇到了 UB用上面的代码?

虽然显式调用析构函数是合法的,但您希望这样做的情况非常罕见(例如,std::vector 在较大的缓冲区中构造和销毁对象)。

请注意,您应该始终将分配器与适当的内存版本、malloc/free、new/delete 等相匹配。虽然运算符 new() 在引擎盖下依赖 malloc 是典型的,但没有要求它这样做,在这种情况下,您的不匹配会产生未定义的结果。