加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – Destroy vs Deallocate

发布时间:2020-12-16 10:24:53 所属栏目:百科 来源:网络整理
导读:在Accelerated C的第11章中,作者提出了一个Vector类,它使用数组模拟std :: vector的行为.他们使用allocator类来处理内存管理. uncreate函数的作用是销毁数组的每个元素并释放为数组分配的空间: template class T void VecT::uncreate() { if (data) { // de
在Accelerated C的第11章中,作者提出了一个Vector类,它使用数组模拟std :: vector的行为.他们使用allocator类来处理内存管理. uncreate函数的作用是销毁数组的每个元素并释放为数组分配的空间:

template <class T> void Vec<T>::uncreate() {
  if (data) {

  // destroy (in reverse order) the elements that were constructed 
  iterator it = avail;
  while (it != data)
    alloc.destroy(--it);

  // return all the space that was allocated
  alloc.deallocate(data,limit - data); 
  }

  // reset pointers to indicate that the Vec is empty again 
  data = limit = avail = 0;
}

显然我们需要释放分配的空间.但我不清楚为什么我们也需要摧毁个别元素.如果我们只在不破坏单个元素的情况下释放内存,会发生什么?

解决方法

原因是它可能会让你陷入困境. C标准第3.8章(对象寿命)第4段解释了为什么(强调我的):

A program may end the lifetime of any object by reusing the storage which the object occupies or by explicitly
calling the destructor for an object of a class type with a non-trivial destructor. For an object of a class type
with a non-trivial destructor,the program is not required to call the destructor explicitly before the storage
which the object occupies is reused or released; however,if there is no explicit call to the destructor or if a
delete-expression (5.3.5) is not used to release the storage,the destructor shall not be implicitly called and
any program that depends on the side effects produced by the destructor has unde?ned behavior.

这意味着可以在由具有普通析构函数(*)的对象或者根本没有一个对象(例如整数等)的对象占用的内存上执行它.但是当内存包含需要在析构函数中执行某些操作的类的对象(如关闭网络连接或文件,刷新缓冲区,释放内存)时,您将泄漏资源(并且通过标准形式,调用未定义的行为).

(*)如果生成的编译器不是虚拟的,则析构函数是微不足道的,并且它所属的类的所有非静态成员和直接基类都具有琐碎的析构函数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读