YiFei YiFei - 1 month ago 5
C++ Question

What's happening when I do new T[1]?

Quick question here:

template <class T>
T* allocate(std::size_t n){
return new T[n];
}


So in the above code, when
n==1
, we're doing
new T[1]
, so I have two worries:

1.I heard that when allocating array, extra memory are used to store the length of the array (unsure though), so would this be malicious when having
new T[1]
a lot, wasting a lot of memory?

2.Should I free this using
delete[]
or simply
delete
?

AnT AnT
Answer
  1. Yes, in a typical implementation when you use new T[n] some extra memory will be required to store the exact length of the array, but only for types with non-trivial destructors.

    E.g. in a typical implementation new int[1] carries no memory overhead compared to new int, but new std::string[1] will carry memory overhead compared to new std::string.

    The extra memory is just an extra size_t field, meaning that percentage-wise it depends on the size of the object you allocated. If sizeof(T) is comparable to sizeof(size_t) the overhead might be considerable.

    But it all might also depend on the additional details of the implementation-specific memory allocation mechanism.

    In other words, if this a part of application-specific code it makes sense to try it and see whether it has any negative impact on your program's memory consumption. Maybe it is not a problem at all. But if you are writing a generic library, then things like that are worth paying attention to.

  2. Yes, you should use delete [].

Comments