"A custom array class", and "dynamic array vs. dynamically allocated array"

Hello!

I have written a generic class as an alternative for <std::vector>. I can't access the full code right now, but here is the gist of it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
template<typename T>
class Array
{
private:
	T* arr;
	unsigned long size;

public:
	void PushBack(T value)
	{
		T* copy = new T[size];
		for (int i = 0; i < size; i++) { copy[i] = arr[i]; }
		arr = new T[size + 1];
		for (int i = 0; i < size; i++) { arr[i] = copy[i]; }
		arr[size] = value;
		size++;
	}
}


First of all, is this a dynamic array or a dynamically allocated array? I assume it is the latter, but, in that case, what is the former?

Secondly, is this a viable implementation, or does this "waste a bunch of memory", for lack of a better expression?

Best regards,
a guy on the Internet
(1) It is both. It is a dynamic array because the size changes at run time. It is dynamically allocated because you allocated the memory on the heap using the new operator.

(2) It is not a viable implementation. It would be better to use the std::vector class. It is, however, a great practice project. The skills you learn implementing practice projects like this will pay big dividends as you become more experienced as a programmer.

A couple of comments:

(a) There is no need to copy the original arr array to the copy array. The original arr memory is never being overwritten. Just do T* copy = arr;

(b) You have a memory leak. Somewhere in the function you have to delete the original arr array (and the copy array if you decide to keep it).
(a) What do you mean?
Like this?:
1
2
3
4
5
T* copy = arr;
arr = new T[size + 1];
for (int i = 0; i < size; i++) { arr[i] = copy[i]; }
arr[size] = value;
size++;

(b) Yes, I know, I have a delete[] in the full code.

Why is it not viable? How would I go about writing a viable one, assuming it's possible to do using pure C++ / C?
(a) Yes. Exactly like that. And then when you are done, just delete[] copy;

I assume you have a constructor for the class that initializes the array to an empty array (arr = NULL, size = 0).

As far as viable, I guess I don't know what you mean. I probably meant "practical". The std::vector is already available, and it probably has more safety built into it than something you would write. It also has features that improve speed and memory copying, etc., that you might not even think about. Why reinvent the wheel when you can be inventing other things?

If you mean "it will work" and can be made robust, then yes, your class could be considered viable.
Last edited on
All right, thank you.
Topic archived. No new replies allowed.