What is C++ version of realloc(), to allocate the new buffer and copy the contents from the old one?

后端 未结 4 1310
北恋
北恋 2020-12-06 10:04

In C we used malloc(), free(), but in C++ youare using new, delete, but in C we also have realloc, which will alloc the new block and

相关标签:
4条回答
  • 2020-12-06 10:19

    realloc isn't used in C++ because C++ wants to use its copy and default constructors and destructors for things like this in general. But if you got plain old types that you want to handle as fast as possible, there is no reason not to roll your own array class that does what you want. I'm surprised there isn't one that's mostly STL-compatible already in the top Google page.

    0 讨论(0)
  • 2020-12-06 10:26

    Let's see what Bjarne Stroustrup thinks!

    Why doesn't C++ have an equivalent to realloc()?

    If you want to, you can of course use realloc(). However, realloc() is only guaranteed to work on arrays allocated by malloc() (and similar functions) containing objects without user-defined copy constructors. Also, please remember that contrary to naive expectations, realloc() occasionally does copy its argument array.

    In C++, a better way of dealing with reallocation is to use a standard library container, such as vector, and let it grow naturally.

    0 讨论(0)
  • 2020-12-06 10:39

    C++ doesn't have a new/delete equivalent of C's realloc.

    The probable reason (although it is not mentioned anywhere in the Standard) is because of constructors that can throw: how should it behave if, while reallocating, a constructor throws? The handling of this case is best left to the programmer because there is not one true answer.

    0 讨论(0)
  • 2020-12-06 10:40

    There's no new/delete equivalent of realloc in C++.

    From Bjarne Stroustrup's FAQ :

    Why doesn't C++ have an equivalent to realloc()?

    If you want to, you can of course use realloc(). However, realloc() is only guaranteed to work on arrays allocated by malloc() (and similar functions) containing objects without user-defined copy constructors. Also, please remember that contrary to naive expectations, realloc() occasionally does copy its argument array. In C++, a better way of dealing with reallocation is to use a standard library container, such as vector, and let it grow naturally.

    If you want a resizeable container, just use std::vector, otherwise stay with malloc, realloc and free.

    And, to answer your last question, the C++ version of your code would be :

    main() {
        std::vector<char> x(3);
        x[0] = 10;
        x[1] = 20;
        x[2] = 30;
        x.resize(4);
        x[3] = 40;
        for (int i = 0; i < 4; i++) std::cout << x[i] << std::endl;
    }
    
    0 讨论(0)
提交回复
热议问题