I have an object O1 which has pointer. I created another object O2 by copy constructor. The pointer address will be copied into the object O2. When i come out of scope of O2, it will be deleted. The destructor will delete the pointer as well. This make the pointers in object O1 become dangling. How to make sure that i delete the pointer only when i come out of O1.
In a short description, how to delete the object pointer only when no others are referring to that pointer directly or indirectly.
class info {
public:
char *buf;
int len;
info(int l) {
len = l;
buf = new char[len];
buf[0] = 'h';
}
~info() {
delete[] buf;
}
};
int main() {
info O1(100);
cout << O1.buf << "\n";
{
info O2(O1);
}
cout << O1.buf << "\n";
}
Here the destructor of O1 at the end of the main will get a SIGABT signal for trying to deallocate a memory referred by O1.buf which is already deleted through O2.