Your AClass
member double* data;
will be copied here:
AClass y = *x;
Since you haven't provided copy/move constructors/assignment operators, the raw pointer will be copied as-is in these situations and delete[] data
will be done by both x
and y
in the destructor.
Mandatory read when dealing with raw pointers:
https://en.cppreference.com/w/cpp/language/rule_of_three
And these:
What is The Rule of Three?
Rule-of-Three becomes Rule-of-Five with C++11?
Here's an example implementation of the member functions mentioned in the above articles. It's a little much - and error prone, which is why it's almost always better to use a standard container.
#include <algorithm>
#include <iostream>
#include <utility>
class AClass {
public:
AClass(size_t len, double val);
// rule of five:
AClass(const AClass& rhs); // copy constructor
AClass(AClass&& rhs); // move constructor
AClass& operator=(const AClass& rhs); // copy assignment
AClass& operator=(AClass&& rhs); // move assignment
~AClass();
private:
size_t length; // use an unsigned type since you only accept unsigned values
double* data;
};
// destructor
AClass::~AClass() {
delete[] data;
}
AClass::AClass(size_t len, double val) :
length(len),
data(new double[length])
{
std::fill_n(data, length, val);
}
// copy constructor
AClass::AClass(const AClass& rhs) :
length(rhs.length),
data(new double[length])
{
std::copy_n(rhs.data, length, data);
}
// move constructor
AClass::AClass(AClass&& rhs) :
length(std::exchange(rhs.length, 0)),
data(std::exchange(rhs.data, nullptr))
{}
// copy assignment
AClass& AClass::operator=(const AClass& rhs) {
double* tmpdata = new double[rhs.length];
delete[] data;
length = rhs.length;
data = tmpdata;
std::copy_n(rhs.data, length, data);
return *this;
}
// move assignment
AClass& AClass::operator=(AClass&& rhs) {
// leave the destruction up to the moved-from object
std::swap(length, rhs.length);
std::swap(data, rhs.data);
return *this;
}
int main() {
AClass* x = new AClass(10, -1.0);
AClass y = *x;
delete x;
}