Well, this statement in your question:
void* foo = new unsigned char[ 40 ];
is allocating 40 bytes of unsigned char
type on the free-store (or heap) i.e. dynamic memory allocation. You can simply avoid pointer operations e.g. casting, increment, decrement, de-reference, etc. by using an array on stack like this:
unsigned char foo[ 40 ];
That is the case when you already know the size e.g. 40 in your question.
So, there are two types of arrays according to lengths: fixed and variable. Fixed-length that you know at compile-time; and, variable-length that you get at run-time. And, from your question, the term "custom" might be referring to "variable-length arrays".
You cannot have a variable-length array on stack in standard C++ so you have to allocate it on free-store using new[]
and de-allocate after use using delete[]
. Though, some compiler extensions also allow variable-length arrays e.g. GCC (See: C++ : Variable Length Array).
So, if you have an array size that you don't know already then the dynamic memory allocation is way to go.
Or, you can simply use an STL container such as std::vector
. It'll handle all the memory management stuff under the hood. And, you can simply start writing your business logic right away instead of spending time on memory management. And, for static fixed-length arrays, you ought to use std::array
with all the good stuff that come with it.
And, if you really want to do memory management stuff yourself, you ought to look at std::unqiue_ptr
and std::shared_ptr
along with std::make_unique
and std::make_shared
wherever applicable depending on your use-cases. That would make life easy by enforcing RAII.
As you're working with raw bytes (guessed it from unsigned char
), you ought to use std::byte
if you can have a C++17-enabled compiler.
Relevant material:
Hope that helps!
If there is more to your use-case, kindly add that detail in your question so that the answer could be more relevant and aligned to that specific use-case.