'Copy'에 해당되는 글 1건

[[ 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
        _ptr = NULL; _len = 0;

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

        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)
    // 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.

블로그 이미지


Tag ,

댓글을 달아 주세요