Can I Allocate a Block of Memory with new?

一笑奈何 提交于 2019-12-13 18:54:27

问题


So given this c structure:

typedef struct {
    int* arr1;
    int* arr2;
} myStruct;

This answer described using a single malloc to allocate a myStruct and it's arrays at the same time:

myStruct* p = malloc(sizeof(*p) + 10 * sizeof(*p->arr1) + 10 * num * sizeof(*p->arr2);

if(p != NULL) {
    p->arr1 = (int*)(p + 1);
    p->arr2 = p->arr1 + 10;
}

What I'd like to know is there a similar way to do this with new?
Obviously I want to be able to allocate to a size that I receive at runtime as is done with the C example.


回答1:


You can allocate a block of memory using new with an array of char, then use placement new to call the constructor on that block of memory.




回答2:


In c++ we use new because it calls the constructors of the objects being allocated. So the proper way to achieve what you want is to have the constructor of the structure do the necessary allocations.




回答3:


Is there any reason you want to do it like in the link you provided? A little more context would help. Otherwise I would personally just use a constructor to do that:

    struct myStruct {
        int* arr1;
        int* arr2;
        myStruct(int num)
        {
                arr1 = new int[10];
                arr2 = new int[10*num];
        }
        ~myStruct()
        {
                delete[] arr1;
                delete[] arr2;
        }
};

int main()
{
        int num = 3;
        myStruct* a;
        a = new myStruct(3);
        delete a;
}


来源:https://stackoverflow.com/questions/19793517/can-i-allocate-a-block-of-memory-with-new

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!