Delete an array of size 1

Perhaps this is a candidate for a one-line answer. I would still know about it.

I am writing a simple circular buffer and for some reasons that are not important for the question that I need to implement using an array of doubles. In fact, I did not invest other ways to do this, but since an array is required, I did not spend much time searching for alternatives.

template<typename T>
class CircularBuffer
{
public:
    CircularBuffer(unsigned int size);
    ~CircularBuffer();
    void Resize(unsigned int new_size);
    ...
private:
    T* buffer;
    unsigned int buffer_size;
};

Since I need to have a dynamic buffer size, buffer_size is neither a constnor a template parameter. Now the question is:

During construction and in the function, Resize(int)I require that the size be at least one, although a size buffer of one is actually no longer a buffer. Of course, using a simple double would be more appropriate, but in any case.

- - . , ? , , delete[] buffer;, , , , buffer = new T[0], delete[] delete buffer; ( )?

, Arne

+3
5

new T[x], delete[], x ≤ 1.

+10

?

+7

delete[] , new[] - . delete - undefined.

+5

1 buffer = new T[1], delete[] buffer. , n = 1 . :: new [] delete []

+1

When you use "delete []", he knows that he has to delete the array of objects - he calls every object destructor in the array. Do not shy away from the standard - this will only give you a ton of headaches. If using a new use, uninstall. When using the new [], use delete []. Just as easy.

0
source

Source: https://habr.com/ru/post/1748829/


All Articles