I hava a class
class vlarray {
public:
double *p;
int size;
vlarray(int n) {
p = new double[n];
size = n;
for(int i = 0; i < n; i++)
p[i] = 0.01*i;
}
~vlarray() {
cout << "destruction" << endl;
delete [] p;
size = 0;
}
};
when I use in main
int main() {
vlarray a(3);
{
vlarray b(3);
b.p[0] = 10;
for(int i = 0; i < 3; i++) {
cout << *(b.p+i) << endl;
}
a = b;
} // the magic happens here deallocation of b
for(int i = 0; i < 3; i++) {
cout << *(a.p+i) << endl;
return 0;
}
when b deallocated smth happens to a .. what is the problem, why that problem occurs and how to avoid such type of problems?
There seems to be some confusion amongst the existing answers on this question, so I am going to jump in.
Immediate issue
Your primary issue is that you have not defined your own copy assignment operator. Instead, the compiler generates a naive one for you, so that when you run
a = b, the pointer insidebis copied intoa. Then, whenbdies and its destructor runs, the pointer now insideais no longer valid. In addition,a‘s original pointer has been leaked.Your own copy assignment operator will need to
deletethe existing array, allocate a new one and copy over the contents from the object you’re copying..More generally
Going further, you will also need to define a few other things. This requirement is neatly summed-up as the Rule of Three (C++03) or Rule of Five (C++11), and there are plenty of explanations online and in your favourite, peer-recommended C++ book that will teach you how to go about satisfying it.
Or, instead…
Better still, you could start using an
std::vectorinstead of manually allocating everything, and avoid this entire mess: