within operator=
, should I check (and perhaps free/delete if not nullptr
) d
before malloc/new an new array for it?
Is the delete[]d
required?
If you are going to allocate a new array with new[]
, then yes, you need to free the the old array with delete[]
, otherwise it will be leaked. Whether you do that before or after allocating the new array is up to you, but I would do it after, in case allocating the new array fails.
Note that you can optimize the code you have shown a little, by skipping the new[]
/delete[]
if the new dim
is the same value as the old dim
, and by using the copy-swap idiom when you do allocate a new array:
VLA(const VLA &other) {
d = new double[other.dim];
memcpy(d, other.d, sizeof(double) * other.dim);
dim = other.dim;
}
VLA& operator=(const VLA &other) {
if (this != &other) {
if (dim == other.dim) {
memcpy(d, other.d, sizeof(double) * other.dim);
else {
VLA temp(other);
std::swap(d, temp.d);
std::swap(dim, temp.dim);
}
}
return *this;
}
Though, you really should should be using std::vector
instead of new[]
/delete[]
manually at all. Let std::vector
handle the array for you:
#include <vector>
struct VLA {
std::vector<double> d;
int dim() const { return d.size(); }
// compiler-generated copy constructor will "do the right thing"...
// compiler-generated operator=() will "do the right thing"...
};