M
M
ManyBytes2022-01-17 21:58:53
C++ / C#
ManyBytes, 2022-01-17 21:58:53

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");
}

2) Overloaded new operator:
void* operator new[](size_t size)
{
        T* ptr = (T*)malloc(sizeof(T) * size);  // T - тип массива
        if (ptr == nullptr)
            throw("Allocation error");

        return ptr;
}

Which option is the most efficient/most used?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
res2001, 2022-01-18
@ManyBytes

which option is the most efficient/most used

Creating a class in dynamic memory is divided into 2 stages:
1. allocation of "raw" memory from the memory manager
2. memory initialization - calling the class constructor on the allocated memory area.
The malloc option doesn't do the second part. In order to end the process in this variant, you need to use allocating new, passing a pointer to the previously allocated memory. Destructors also need to be called explicitly.
If the variant with malloc is brought to its logical end, then it will do the same thing as the variant with new, there are no advantages here. But do not forget about the explicit call of the destructor.
When deleting a class from dynamic memory, there are reverse steps: calling the destructor and freeing the memory.
malloc is usually used in plus code when they implement their own allocators and need a "raw" uninitialized memory block. But in this case, it is quite possible to do without malloc - usenew char[MEM_SIZE]

M
Mercury13, 2022-01-18
@Mercury13

But plain new throws out std::bad_alloc.
So it's not entirely clear what you want to do when you do new with the "don't throw" flag, and then throw an accident on a failed new.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question