Answer the question
In order to leave comments, you need to log in
How to correctly allocate memory (with allocation check) for an array of a class?
When creating simple libraries, I ran into a misunderstanding of what is preferable to use to allocate memory for arrays in a class:
1) A function based on new / new(std::nothrow):
void alloc(size_t size)
{
m_data = new(std::nothrow) T[size]; // m_data - указатель на массив, T - тип массива
if (m_data == nullptr)
throw std::runtime_error("Allocation error");
}
void* operator new[](size_t size)
{
T* ptr = (T*)malloc(sizeof(T) * size); // T - тип массива
if (ptr == nullptr)
throw("Allocation error");
return ptr;
}
Answer the question
In order to leave comments, you need to log in
which option is the most efficient/most used
new char[MEM_SIZE]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question