简体   繁体   English

堆对象内部的本地数组-C ++

[英]Local array inside Heap object - C++

For the purpose of the example - I have a few classes: 出于示例的目的-我有几个类:

class RGB {
    short value[3];
};

class AbstractImage {
    protected:
        int n_pixels;

    public:
        virtual ~AbstractImage() {};
}

template <typename T> class Image : public AbstractImage {
    T* data;

    public:
    Image<T>(int n) { n_pixels=n; data=new T[n_pixels]; }
    virtual ~Image<T>() {delete[] data;}

    // also provided is a copy constructor and assignment operator overloading

};
typedef class Image<RGB> ColorImage;

Is there a memory leak from Image? Image是否存在内存泄漏? Do I need to release the RGB objects one by one with delete? 是否需要通过Delete一次释放RGB对象? Or isn't there a leak? 还是没有泄漏?

From my understanding: data points to content created on the heap (using the word "new") which holds an RGB object array with a size of n_pixels (which has an array called "value" with 3 cells - also on the heap). 根据我的理解:数据指向在堆上创建的内容(使用单词“ new”),该内容包含一个大小为n_pixels的RGB对象数组(该数组具有一个名为“ value”的数组,该数组带有3个单元格-也在堆上)。 Which means that we need to delete each object one by one. 这意味着我们需要一个一个地删除每个对象。

Is there a memory leak from Image? Image是否存在内存泄漏?

No. You match your new[] with delete[] . 不。您将new[]delete[]匹配。 Though of course, it may leak if you leak the containing Image object, and never destroy it . 当然,如果泄漏包含的Image对象,并且永不破坏 ,则可能泄漏。 Your inclusion of a virtual destrcutor (which I presume means you delete pointers to AbstractImage ) ensure the most derived class cleans up after itself. 包含一个虚拟析构函数(我认为这意味着您delete指向AbstractImage指针),以确保最派生的类在其自身之后被清除。

Do I need to release the RGB objects one by one with delete? 是否需要通过Delete一次释放RGB对象?

No, since you didn't allocate any of them individually with new . 不,因为您没有使用new单独分配它们。 Each and every member of your dynamically allocated array lies in the allocated block. 动态分配的数组的每个成员都位于分配的块中。 It's default initialized when you allocate the array, and then has its destructor called when you delete[] the entire array. 当您分配数组时,它是默认初始化的,然后在delete[]整个数组时, delete[]调用它的析构函数。 The language specification has it covered. 语言规范对此进行了介绍。

Having said all that, if you need to manage a buffer of objects, using std::vector is almost always the superior alternative. 话虽如此,如果您需要管理对象缓冲区,那么使用std::vector几乎总是更好的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM