[[ 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.
'Language > C&C++' 카테고리의 다른 글
[C/C++] Using static variable in large-size-file. (0) | 2008.09.09 |
---|---|
[C/C++] Indirect branch... (0) | 2008.07.26 |
[C/C++] Using Reference as function parameter... (0) | 2008.05.02 |
[C++] C++ Pointer fixups... (0) | 2008.04.26 |
[C/C++] Simple example of using 'typename' (0) | 2008.04.22 |