C ++中的析构函数 [英] Destructors in C++

查看:176
本文介绍了C ++中的析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

析构函数释放分配给它所属的对象的内存,还是只调用它,以便它可以在对象被编译器释放之前执行一些最后一分钟的内务处理?

Does the destructor deallocate memory assigned to the object which it belongs to or is it just called so that it can perform some last minute housekeeping before the object is deallocated by the compiler?

推荐答案

编译器不会删除任何内容。

The 'compiler' doesn't delete anything. It creates code that does things at runtime.

当编写 delete somePointer; 编译器时, :

  if ( has_virtual_destructor( * somePointer  ) ) {
       // virtual dispatch to a compiler-generated function
      dynamic_cast< true_dynamic_type * >(somePointer)->destroy_dynamic_type();
       /* contents of true_dynamic_type::destroy_dynamic_type() {
              this->~true_dynamic_type();
              operator delete( this); // executed within class context
       } */
  } else {
      somePointer->~ClassName();
      operator delete(somePointer);
  }

换句话说,析构函数被调用,然后operator delete被调用释放存储空间。

In other words, the destructor gets called, and then operator delete gets called to free the storage.

如果析构函数是虚拟的,则使用虚拟分派以最大衍生的形式对对象执行整个操作。一个常见的实现方法是给每个虚拟析构函数添加隐藏参数。

If the destructor is virtual, a virtual dispatch is used to perform the entire operation on the object in its most-derived form. A common way of implementing this is to add hidden arguments to every virtual destructor.

请注意,顶层if语句并不是生成代码的一部分。编译器在编译时做出这个决定。

Note that the top-level if statement isn't really part of the generated code; the compiler makes that decision at compile-time.

这篇关于C ++中的析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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