In C++ you may come across an issues where you need to use a copy constructor. This is because when a class is assigned from one variable to another it has to copy the values across. If we are dealing with pointers that are inside the
class then the pointer will be copied. So this can create and issue if the pointer is deallocated in the destructor. Since now there is two copied of the same pointer which is going to be deallocated twice. This will result in a common issue such as a double free.
In this short program you can see the effect here that will cause a double free. In this case I am using "malloc" to keep the example short. The following program will crash when the main function returns as it will call free from the destructor twice on the same pointer value.
class MyClass {
public:
char *buf;
size_t buf_len;
MyClass(size_t len) {
printf("Alloc\n");
buf_len = len;
buf = (char *) malloc(len * sizeof(buf));
}
~MyClass() {
printf("Free\n");
free(buf);
}
};
int main(int argc, char **argv) {
MyClass x = MyClass(4096);
MyClass y = x;
return 0;
}
To get another the issue above in C++ we must use a copy constructor which will allow us to override the default functionality when the class is copied in order to allocate and copy the contents of the buffer and a new pointer which will completely separate the source class from the new class that is being assigned.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
class MyClass {
public:
char *buf;
size_t buf_len;
MyClass(size_t len) {
printf("Alloc\n");
buf_len = len;
buf = (char *) malloc(len * sizeof(buf));
}
~MyClass() {
printf("Free\n");
free(buf);
}
MyClass(const MyClass &source)
{
buf_len = source.buf_len;
buf = (char *) malloc(buf_len * sizeof(buf));
memcpy(buf, source.buf, buf_len);
}
};
int main(int argc, char **argv) {
MyClass x = MyClass(4096);
MyClass y = x;
return 0;
}
Did You find this page useful?
Yes
No