element c'tor/d'tor in array created with realloc/free

I create a dynamic array (like std::vector without capacity() ).
It can initialize their element (Init = true) or not (for primitive data types only).

It seems that resize() member working but I have my doubts in the last if block where the comment is.

I use this strategy because realloc is much better from new when you shrink the memory block.

Finally, I check a delete[](void*,void*) function. I fail to write it correct. Is this function an inplace destructor caller like inplace new?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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;
		}
		else if (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;
		}
		else if (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.
+1 @ Chameleon.

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
Last edited on
Topic archived. No new replies allowed.