[C/C++] Take care of using shallow copy!

There is copy construction in C++. And default copy constructor does shallow copy. But, we should take care of shallow-copied-instance. Every programmer knows about this issue. But, sometimes, it is difficult to detect mistake from shallow copy. Here is an example.

// a.h
class A
{
public:
    A(void){
        _ptr = NULL; _len = 0;
    }

    A(int len){
        _len = len;
        _ptr = malloc(_len);
    }

    ~A(void){
        if(NULL != _ptr) { free(_ptr); }
    }

    void*  _ptr
    int _len
};

-------

// file1.c
static A gA(100); // --- (*a)
void getA (A& param)
{
    A = gA;
}

// file2.c
void function (void)
{
    A localA; // --- (*1)
    getA(localA);
    ...
    // do something with localA.
    ...
}

In this case, ‘localA'(*1)’s destructor is called at the moment of returning from the function. And at that time, memory of ‘gA._ptr’ is freed, because ‘localA’ is shallow copy of ‘gA’.
Stack variable is automatically(implicitly) destructed when function is returned. And this is not easy to realize without keeping it in mind.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s