Resizing in C ++ is inconvenient due to the potential need to call constructors and destructors.
I don't think there is a fundamental reason why in C ++ you couldn't have a resize[] statement with new[] and delete[] , something similar to this:
newbuf = new Type[newsize]; std::copy_n(oldbuf, std::min(oldsize, newsize), newbuf); delete[] oldbuf; return newbuf;
Obviously, oldsize will be retrieved from a secret location, the same thing happens in delete[] , and Type on the type of operand. resize[] will fail if the type is not copied - this is correct, since such objects simply cannot be moved. Finally, the above code creates objects by default, which you would not want to use as actual behavior, by default.
There is a possible optimization, where newsize <= oldsize , to call destructors for objects "past the end" of the newly created array and do nothing else. The standard would be to determine if this optimization is required (for example, if you resize() vector), resolved, but undefined, resolved, but implementation-dependent or forbidden.
The question you should ask yourself is "is it really useful to provide this, given that it also does vector and is specifically designed to provide a container with a resizable (contiguous memory - this requirement is omitted) in C ++ 98, but fixed in C ++ 03), which is better than arrays with C ++ ways of doing things?
I think the answer is widely considered no. If you want to make resizingable C buffers in a way, use malloc / free / realloc , which are available in C ++. If you want to make resizable buffers in C ++, use a vector (or deque if you really don't need continuous storage). Do not try to mix them with new[] for raw buffers unless you are implementing a vector container.
Steve Jessop Aug 14 '10 at 12:36 2010-08-14 12:36
source share