سؤال

Is there a any difference in terms of memory allocation between

struct_type * mystruct = new struct_type();

and

struct_type *mystruct = new struct_type[1];

?

هل كانت مفيدة؟

المحلول

It depends on what you mean by "difference in memory allocation".

Firstly, new and new[] are two independent memory allocation mechanisms, which can (and will) allocate memory with different internal layout, e.g. with different implementation-dependent household information associated with allocated memory block. It is important to remember that the first allocation has to be paired with delete and the second - with delete []. Also, for this reason, in a typical implementation the second allocation might consume more memory than the first.

Secondly, the initializer syntax () you used in the first allocation triggers value-initialization of the allocated object. Meanwhile, in your second allocation you supplied no initializer at all. Depending on the specifics of struct_type class, this can lead to significant differences in initialization. For example, if struct_type is defined as struct struct_type { int x; }, the first allocation is guaranteed to set mystruct->x to zero, while the second one will leave a garbage value in mystruct->x. You have to do new struct_type[1]() to eliminate this (probably unintended) difference.

نصائح أخرى

They will allocate same amount visible/usable of memory, namely memory required to hold one object. But the semantics are different, former is a pointer to single object, while latter is an array containing one object. And when de-allocating you should use

delete mystruct;

in first case while

delete []mystruct; 

in second case.

Another difference is compiler must hold some book-keeping information about the latter case, for example it must know the number of items in the array, so that it can be deleted correctly. And of course your structure must have a default constructor in to be used in latter case.

The first line would create a structure object and return its address to your pointer. The second line would create an array of 1 structure object and return the starting address of the array to your pointer

I think there is no difference in terms of memory allocation between these two lines of code.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top