zoukankan      html  css  js  c++  java
  • removing objects from an array

    I am creating a program that uses an array of objects declared with

    Element* elements =newElement[number];

    where an element is a class that has/needs a its own destructor.

    when I go to delete this would I use just use array delete, and have the program worry about calling the destructor:

    delete[] elements;

    or do I call the destructor for each item explicitly with keyword delete:

    for(int ii =0; ii<ArraySize; ii++)
        delete elements[ii];
    delete[] elements;

    Note: I understand that I could probably use something like boost::ptr_vector, but I wanted similar to hashTable functionality (so the for loop would need additional information, but that is outside of the direct scope of this question) which is why I am using a traditional array. I would still like to know which behavior is needed to avoid memory leaks.

    解答:

    第一个是正确的,第二个会得到编译错误。

    这个问题主要的问题其实是对于多位数组的动态内存分配的问题。比如我们不能直接使用int* p=new int[4][3];等的的。

    而是应该借鉴下面的例子:

    elements = new Element *[rows];
    for (int i=0; i<rows; i++)
        elements[i] = new Element[row_len];
    

      然后采用:

    for (int i=0; i<rows; i++)
        delete [] elements[i];
    delete [] elements;
    

      原文地址:http://stackoverflow.com/questions/10425354/removing-objects-from-an-array

  • 相关阅读:
    WCF Data Contract之集合类型
    LINQ To DataSet
    WCF Data Contract之枚举
    初识Parallel Extensions之TPL(二)
    初识Parallel Extensions之TPL
    java北京行之单例模式的引入
    Strut2 入门
    解决 Eclipse 下使用 Ant 编译出现问题: 警告:编码 GBK 的不可映射字符
    解决 Ant 非法字符: \65279
    [原创]Visual Studio 中引用 Flash 控件
  • 原文地址:https://www.cnblogs.com/rollenholt/p/2480881.html
Copyright © 2011-2022 走看看