释放动态数组的最后一个元素 [英] Freeing last element of a dynamic array

查看:179
本文介绍了释放动态数组的最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

int * array=new int[2];

我想释放最后一个元素的内存,因此将分配的内存减少到只有1个元素。我试图调用

and I would like to free the memory of the last element, thus reducing the allocated memory to only 1 element. I tried to call

delete array+1;

但它给错误


*** glibc detected *** skuska:
free():invalid pointer:0x000000000065a020 *

这可以在C ++ 03中完成,而不需要显式重新分配?

Can this be done in C++03 without explicit reallocation?

注意:如果我想使用一个类而不是一个基本的数据类型像int),我如何释放内存,以便调用类的析构函数?

Note: If I wanted to use a class instead a primitive datatype (like int), how can I free the memory so that the destructor of the class is called too?

注意2:我试图实现 vector :: pop_back

推荐答案

不要使用 new [] 表达式为此。这不是矢量如何工作。你所做的是分配一大堆原始内存。您可以使用malloc,或者您可以使用运算符新的,其中与新表达不同。这基本上是 reserve()成员函数 std :: vector 的假设,假设你已经使用了默认分配器。它不会以 new [] 表达式的方式创建任何实际对象。

Don't use new[] expression for this. That's not how vector works. What you do is allocate a chunk of raw memory. You could use malloc for this, or you could use operator new, which is different from the new expression. This is essentially what the reserve() member function of std::vector does, assuming you've used the default allocator. It doesn't create any actual objects the way the new[] expression does.

当您要构建一个元素,您使用刊登位置新,将其传送到原始记忆中的某个位置你已经分配了当你想要删除一个元素时,你直接调用它的析构函数。完成后,如果您使用 delete [] 表达式,则使用 operator delete $ c> operator new ,或者您使用 free()如果您使用 malloc

When you want to construct an element, you use placement new, passing it a location somewhere in the raw memory you've allocated. When you want to destoy an element, you call its destructor directly. When you are done, instead of using the delete[] expression, you use operator delete if you used operator new, or you use free() if you used malloc.

下面是一个创建10个对象的示例,并以相反的顺序进行删除。我可以按任何顺序摧毁它们,但是这是你如何在一个向量实现中执行的。

Here's an example creating 10 objects, and destoying them in reverse order. I could destroy them in any order, but this is how you would do it in a vector implementation.

int main()
{
    void * storage = malloc(sizeof(MyClass) * 10);

    for (int i=0; i<10; ++i)
    {
        // this is placement new
       new ((MyClass*)storage + i) MyClass;
    }

    for (int i=9; i>=0; --i)
    {
        // calling the destructor directly
        ((MyClass*)storage + i)->~MyClass();
    }

    free(storage);
}

pop_back 将会通过简单地调用最后一个元素的析构函数来实现,并将大小成员变量递减1.它不会(而且不能,而不是一堆不必要的副本)释放任何内存。

pop_back would be implemented by simply calling the destructor of the last element, and decrementing the size member variable by 1. It wouldn't, shouldn't (and couldn't, without making a bunch of unnecessary copies) free any memory.

这篇关于释放动态数组的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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