I wrote a template class with one int
member and a generic-typed pointer member. The pointer member will be used as an array, and it will store sideCount
amount of elements. When instantiating an object, it will take an int value for sideCount
and an array of any type that is the size of sideCount
and is already initialized with values.
I wrote 2 versions of this class. For the first one, I didn't specifically allocate any memory for my pointer member:
template <class T>
class die_v1
{
private:
int sideCount;
T* valuesOfSides;
public:
die_v1() : sideCount(0), valuesOfSides(nullptr) {}
die_v1(int sc, T* vos) : sideCount(sc), valuesOfSides(vos) {}
};
For the second one, I dynamically allocated memory for valuesOfSides
using new[]
:
template <class T>
class die_v2
{
private:
int sideCount;
T* valuesOfSides;
public:
die_v2(int sc, T* vos) : sideCount(sc)
{
valuesOfSides = new T[sideCount];
for (int i = 0; i < sideCount; ++i)
valuesOfSides[i] = vos[i];
}
~die_v2() { delete[] valuesOfSides; }
};
My question is, do I need to specifically allocate memory for valuesOfSides
as I did in the second version?
The reason I am asking this is, for the second version, I know exactly what is going on. I'm allocating memory for valuesOfSides
with the size of sideCount
and I'm assigning it with the data in the parameter array. For the first version, I just know it works when I initialize it with the member initializer list, does it have a size? If so, is it the size of the array that I sent from main()
? It looks more clean and efficient since I don't have to allocate any memory, and I don't need a destructor.
Does the die_v2
provide any code stability compared to die_v1
? Or is it the same thing with more steps?