Realloc equivalent in C ++

Yes, another realloc vs. question std::vector . I know what you are going to say, and I agree, forget about allocating memory manually and just use std::vector . Well, unfortunately, my professor forbade me to use anything from the STL for this assignment.

So, I have a dynamic array T , and I need it to resize, and I cannot use std::vector . I could go back to the dark ages and do everything with malloc and family, but if I could use new , that would be awesome.

I read a lot to everyone where they said "no, you can’t do this, use std::vector ", but they were all published before August 2011, and I hope not to hope that something has changed since the dawn of C + + 11. So tell me, I’m lucky, or do I need to return to C-style memory allocation?

+4
source share
2 answers

You should completely avoid realloc because you cannot move C ++ objects like this.

  • Use buf = new unsigned char[sizeof(T) * capacity] to create a new buffer
  • Pass the selected unsigned char * to T * and use these T -pointers from now on
  • Build new elements through "placing new ", as in new (&buf[i]) T(original_copy)
  • To copy a buffer to a larger buffer, first assign a new one, use std::uninitialized_copy (not std::copy ), then destroy the elements in the old one with buf[i].~T() and free the old buffer using delete [] buf .

All of this suggests that you don’t have to worry about exception safety, which is probably suitable for the destination.
Just keep in mind that in real-world code, you must guarantee the safety of exceptions, and this is much more tedious than that.

+6
source

The problem with realloc is that it can move existing data to a different range of contiguous addresses. If you need to do this, given that the C function copies the data without any restrictions on the life of the C ++ object:

  • Constructors
  • copy / move not used
  • destructors are not subsequently called for source objects

This can lead to fatal consequences - for example, when roaming objects contain pointers / links that remain pointers to addresses in the freed memory area.

Unfortunately, the usual malloc implementations do not allow you to use a callback that allows you to replace the code for copying content with your own C ++ - a safe implementation option. If you decide, you can try to find a more flexible malloc library, but it is unlikely to be worth the hassle and risks.

Therefore, in the general case, you should use new to change your capacity, copy / move each object, and delete descendants.

If you are sure that your data is simple enough that moving memcpy style will not lead to adverse consequences, you can use realloc (at your own risk).

+6
source

All Articles