template<class T, bool Init = true>
struct dynamic_array
{
.................................
void resize(size_type n)
{
if (!n && this->n)
{
if (Init) for (auto z = b; z < b + this->n; z++) z->~T();
free(b);
b = 0; this->n = 0;
}
elseif (n < this->n)
{
if (Init) for (auto z = b + n; z < b + this->n; z++) z->~T();
T *bb = (T*) realloc(b, n * sizeof(T));
if (!bb) throw std::bad_alloc();
b = bb; this->n = n;
}
elseif (n > this->n)
{
T *bb = (T*) realloc(b, n * sizeof(T));
if (!bb) throw std::bad_alloc();
///TODO: What about move c'tors from previous memory block to new?
/// It is a MUST or not?
/// How can implement it with this strategy?
if (Init) new(bb + this->n) T[n - this->n];
b = bb; this->n = n;
}
}
protected:
T *b = 0;
size_type n = 0;
};
Nope.
You cannot use realloc because you must run move constructor of moved objects.
If you use realloc, old buffer will be free and you cannot run element move c'tors.
malloc/realloc do not play nice with complex data types, which is why their usage in C++ should be avoided.
If you're worried about strategy when shrinking the buffer.... just don't shrink the buffer. A good/flexible container of this style will typically have more memory allocated than is actually in use... this prevents unnecessary buffer moves (which is why vector differentiates between size and capacity).
EDIT: oh crap, OP is also chameleon. Replying to your own post = I'm confused. XD