I am new to C++ and encountered a problem that I did not understand.
I intended to use a custom cctor dCopy(int)
to create an instance A and use a copy cctor dCopy(const dCopy&)
to create a deep copy of A.
Here is the code:
#include <iostream>
using std::cout;
using std::endl;
class dCopy {
public:
int *a;
dCopy(int);
dCopy(const dCopy &);
~dCopy();
};
// implementation
dCopy::dCopy(int b) {
a = new int(b);
}
dCopy::dCopy(const dCopy & other) {
dCopy(*other.a);
}
dCopy::~dCopy() {
delete a;
a = nullptr;
cout << "It seems that there is no memory leakage." << endl;
}
//main
int main() {
dCopy A(1);
dCopy B(A);
}
The entire code cause the error of "pointer being freed was not allocated."
The issue I found is the implementation of dCopy(const dCopy & other)
If I directly call the custom cctor will cause the error.
dCopy::dCopy(const dCopy & other) {
dCopy(*other.a);
}
However, If I write in this way the error was gone.
dCopy::dCopy(const dCopy & other) {
a = new int(*other.a)
}
However, from my understanding, calling dCopy(*other.a)
is the same with a = new int(*other.a)
but I am not so sure.
Is it because the right implementation created a new instance of a?