'Copy'에 해당되는 글 1건

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

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

Language/C&C++ 2008.06.04 23:41
[[ blog 이사 과정에서 정확한 posting날짜가 분실됨. 년도와 분기 정도는 맞지 않을까? ]]

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.

신고
tags : ,
Trackback 0 : Comment 0

티스토리 툴바