以什么方式是:: operator new []()不同于:: operator new()? [英] In what way is ::operator new[]() different than ::operator new()?

查看:119
本文介绍了以什么方式是:: operator new []()不同于:: operator new()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从之前分配的内存块中构造一个对象数组。但是,我不明白 :: operator new []() :: operator new()从用户角度分配该块时,因为它们都需要块的大小。在下面的示例中,使用任一个似乎具有相同的效果。我缺少某些东西?

I need to construct an array of objects from a previously allocated block of memory. However, I cannot understand in what way ::operator new[]() is different from ::operator new() from the user point of view when allocating that block, since both require the size of the block. In the following example, using either one seems to have the same effect. Am I missing something?

class J {
};

int main() {
    const int size = 5;

    {
        J* a = static_cast<J*> (::operator new[](sizeof (J) * size));
        for (int i = 0; i < size; i++)
            new (&a[i]) J();
        for (int i = 0; i < size; i++)
            a[i].~J();
        ::operator delete[] (a);
    }

    {
        J* a = static_cast<J*> (::operator new(sizeof (J) * size));
        for (int i = 0; i < size; i++)
            new (&a[i]) J();
        for (int i = 0; i < size; i++)
            a[i].~J();
        ::operator delete (a);
    }
}


推荐答案

'

使用 new [] 是它为要分配的数组的每个元素调用构造函数。 delete [] 对析构函数也是一样。

The point of using new [] is that it calls the constructor for each and every element of the array being allocated. delete[] does the same for the destructors.

您正在使用 new 并手动调用构造函数和析构函数,缺少整个点。

You're using placement new and manually calling the constructors and destructors, missing the whole point.

这篇关于以什么方式是:: operator new []()不同于:: operator new()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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