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;
}




Last Modified: 12 December 2016

Releated Posts


2013-08-22 - CPP - Prevent an object by being copied with boost::noncopyable
2013-03-29 - CPP - Why you need a copy constructor
2013-03-27 - CPP -boost::optional
2012-11-06 - C++ - Stringstream example
2012-08-09 - C++ - Check an IP Address is in a IP Mask
2012-06-30 - CPP - Creating A basic python wrapper
2012-06-16 - CPP - Using gperf
2012-05-10 - CPP - Optional function arguments
2012-03-19 - CPP - Read / Write std::map to a file.