Regrow memory allocated by operator new()?

后端 未结 4 1692
心在旅途
心在旅途 2021-01-22 03:59

Is it possible to regrow memory allocated by operator new(), when allocated this way:

char* buf = new char[60];

The C++ FAQ states

相关标签:
4条回答
  • 2021-01-22 04:43

    std::vector

    0 讨论(0)
  • 2021-01-22 04:53

    The correct way is to not do it.

    Simply allocate new memory if the previous allocation wasn't big enough.

    Or use std::vector which wraps all this functionality very efficiently.

    0 讨论(0)
  • 2021-01-22 04:59

    The correct way is to use std::vector or std::string depending on your particular usage of the array--let C++ handle allocation for you.

    If you must use new, you'll have to reallocate and copy the memory. This simple templated function shows you the basics:

    template <typename T>
    T *GrowArray(T *oldArray, size_t oldCount, size_t newCount) {
        T *newArray = new T[newCount];
        if (oldArray) {
            std::copy(oldArray, oldArray + std::min(oldCount, newCount), newArray);
            delete[] oldArray;
        }
        return newArray;
    }
    

    Note that, in most implementations and with most use cases, this is essentially what realloc() does, minus the type safety. If this looks inefficient to you, well, realloc() probably isn't doing anything better.

    0 讨论(0)
  • 2021-01-22 05:00

    The only way is to do a second new, copy the content and then delete the old memory block:

    char *tmpbuff = new char[70];
    memcpy(tmpbuff, buff, 60 * sizeof(char));
    delete [] buff;
    buff = tmpbuff;
    

    (No...C++ is not equal to STL, so there is a life without STL :-) )

    0 讨论(0)
提交回复
热议问题