성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
[정성태] 저렇게 조각 코드 말고, 실제로 재현이 되는 예제 프로젝트를 압...
[정성태] Modules 창(Ctrl+Shift+U)을 띄워서, 해당 Op...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>DLL에 정의된 C++ template 클래스의 복사 생성자 문제</h1> <p> 다음의 예제 클래스를 보겠습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > #include "stdafx.h" class MyClass { int _a = 0; public: MyClass() { } MyClass(int a) { _a = a; } void Print() { printf("%d\n", _a); } }; int main() { MyClass inst(6); // 사용자가 제공한 생성자 호출 inst.Print(); MyClass <span style='color: blue; font-weight: bold'>inst2(inst)</span>; // 기본 복사 생성자 호출 inst2.Print(); MyClass <span style='color: blue; font-weight: bold'>inst3 = inst</span>; // 기본 복사 생성자가 호출되는 또 다른 유형 inst3.Print(); return 0; } /* 출력 결과: 6 6 6 */ </pre> <br /> C++은 사용자가 정의하지 않은 경우 다음과 같은 복사 생성자를 기본으로 제공합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > <span style='color: blue; font-weight: bold'>MyClass(const MyClass &obj)</span> { _a = obj._a; } </pre> <br /> 그렇기 때문에 위의 소스 코드에서 출력 결과가 모두 6이 나온 것입니다. 일반적으로 기본 복사 생성자는 primitive 타입의 멤버 변수를 가진 class에게는 충분히 사용할만합니다.<br /> <br /> 문제는, 포인터 멤버 변수가 들어간 경우입니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > class MyClass { int _a = 0; <span style='color: blue; font-weight: bold'>wchar_t *_pName = nullptr;</span> public: MyClass() { } MyClass(int a, wchar_t *pName) { _a = a; SetName(pName); } void SetName(wchar_t *pName) { <span style='color: blue; font-weight: bold'>if (_pName != nullptr) { delete [] _pName; } _pName = new wchar_t[wcslen(pName) + 1]; wcscpy(_pName, pName);</span> } void Print() { wprintf(L"%d, %s\n", _a, _pName); } }; int main() { MyClass inst(6, L"test"); <span style='color: blue; font-weight: bold'>inst.Print();</span> MyClass inst2 = inst; MyClass inst3(inst); inst.<span style='color: blue; font-weight: bold'>SetName(L"test2");</span> <span style='color: blue; font-weight: bold'>inst2.Print(); inst3.Print();</span> return 0; } /* 출력 결과: 6, test 6, test2 6, test2 */ </pre> <br /> 보는 바와 같이, inst 변수에 대해서만 SetName으로 이름을 바꿨는데도, 그 이전에 값 복사가 이뤄졌던 inst2, inst3에 대해서도 이름이 바뀌어서 출력되고 있습니다. 왜냐하면, 이럴 때 제공되는 C++ 컴파일러의 기본 복사 생성자는 다음과 같기 때문입니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > MyClass(const MyClass &obj) { _a = obj._a; <span style='color: blue; font-weight: bold'>_pName = obj._pName;</span> } </pre> <br /> 그런데, 사실 MyClass에서는 소멸자 정의가 빠져있습니다. 따라서 다음과 같은 코드를 추가해야 하는데,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > <span style='color: blue; font-weight: bold'>~MyClass()</span> { if (_pName != nullptr) { <span style='color: blue; font-weight: bold'>delete[] _pName;</span> } } </pre> <br /> 변경 후, 예제 코드를 실행하면 이제는 다음과 같은 예외가 발생합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Debug Assertion Failed! Program: ...s\ConsoleApplication1\Debug\ConsoleApplication1.exe File: minkernel\crts\ucrt\src\appcrt\heap\debug_heap.cpp Line: 904 Expression: _CrtIsValidHeapPointer(block) </pre> <br /> 이유는 간단합니다. main 함수의 scope가 벗어날 때 inst, inst2, inst3에 대해 소멸자 함수가 실행될 텐데, 한 번만 할당된 _pName 영역을 inst.~MyClass 소멸자에서 이미 해제를 한 상태에서 inst2.~MyClass, inst3.~MyClass를 통해 중복 해제를 시도하기 때문입니다.<br /> <br /> 따라서, 이렇게 포인터가 포함된 클래스를 정의한 경우에는 자연스럽게 사용자가 직접 복사 생성자를 정의해 줘야만 합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > #include "stdafx.h" class MyClass { int _a = 0; wchar_t *_pName = nullptr; public: MyClass() { } MyClass(int a, wchar_t *pName) { _a = a; SetName(pName); } <span style='color: blue; font-weight: bold'>MyClass(const MyClass &obj) { _a = obj._a; SetName(obj._pName); }</span> ~MyClass() { if (_pName != nullptr) { delete[] _pName; } } void SetName(wchar_t *pName) { if (_pName != nullptr) { delete [] _pName; } _pName = new wchar_t[wcslen(pName) + 1]; wcscpy(_pName, pName); } void Print() { wprintf(L"%d, %s\n", _a, _pName); } }; int main() { MyClass inst(6, L"test"); inst.Print(); MyClass inst2 = inst; MyClass inst3(inst); inst.SetName(L"test2"); // inst에 대해서만 이름이 바뀌고, inst2.Print(); // inst2와 inst3는 이전의 이름값이 보관됨. inst3.Print(); return 0; } /* 출력 결과: 6, test 6, test 6, test */ </pre> <br /> 참고로, <span style='color: blue; font-weight: bold'>올바른 복사 생성자 없이</span> STL 컨테이너 클래스를 다음과 같은 식으로 사용해도 동일한 오류가 발생합니다. <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > int main() { MyClass inst(6, L"test"); vector<MyClass> v; v.push_back(inst); // 복사 생성자가 호출되어 vector에 추가되므로, return 0; // scope를 벗어나는 시점에 inst.~MyClass()와 v[0].~MyClass() 소멸자가 호출되므로! } </pre> <br /> <hr style='width: 50%' /> <br /> 자, 이제 MyClass를 별도의 DLL 프로젝트로 분리해 보겠습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > #pragma once #ifdef WIN32PROJECT1_EXPORTS <span style='color: blue; font-weight: bold'>#define WIN32PROJECT1_API __declspec(dllexport)</span> #else #define WIN32PROJECT1_API __declspec(dllimport) #endif #include <string> using namespace std; class <span style='color: blue; font-weight: bold'>WIN32PROJECT1_API</span> MyClass { int _a = 0; wchar_t *_pName = nullptr; public: MyClass() { } MyClass(int a, wchar_t *pName) { _a = a; SetName(pName); } MyClass(const MyClass &obj) { _a = obj._a; SetName(obj._pName); } ~MyClass() { if (_pName != nullptr) { delete[] _pName; } } void SetName(wchar_t *pName) { if (_pName != nullptr) { delete[] _pName; } _pName = new wchar_t[wcslen(pName) + 1]; wcscpy(_pName, pName); } void Print() { wprintf(L"%d, %s\n", _a, _pName); } }; </pre> <br /> 그런 다음 콘솔 프로젝트를 만들어 테스트해봅니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > #include "stdafx.h" #include "../Win32Project1/Win32Project1.h" #pragma comment(lib, "..//Out//Win32Project1.lib") int main() { MyClass inst(6, L"test"); inst.Print(); MyClass inst2 = inst; MyClass inst3(inst); inst.SetName(L"test2"); inst2.Print(); inst3.Print(); return 0; } /* 출력 결과: 6, test 6, test 6, test */ </pre> <br /> 별다른 이상 없이 잘 호출됩니다. 한번 더 변형을 해볼까요? ^^ MyClass를 export하지 않고 다음과 같이 template으로 정의한 후,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > #pragma once #ifdef WIN32PROJECT1_EXPORTS #define WIN32PROJECT1_API __declspec(dllexport) #else #define WIN32PROJECT1_API __declspec(dllimport) #endif #include <string> using namespace std; <span style='color: blue; font-weight: bold'>template<typename T> class MyClass</span> { T _a = 0; wchar_t *_pName = nullptr; public: MyClass() { } MyClass(T a, wchar_t *pName) { _a = a; SetName(pName); } MyClass(const MyClass &obj) { _a = obj._a; SetName(obj._pName); } ~MyClass() { if (_pName != nullptr) { delete[] _pName; } } void SetName(wchar_t *pName) { if (_pName != nullptr) { delete[] _pName; } _pName = new wchar_t[wcslen(pName) + 1]; wcscpy(_pName, pName); } void Print() { wprintf(L"%d, %s\n", _a, _pName); } }; <span style='color: blue; font-weight: bold'>typedef MyClass<int> MyIntClass;</span> </pre> <br /> DLL 측에서 이 클래스를 사용하는 함수를 정의해 export 시킵니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > WIN32PROJECT1_API void Func1(<span style='color: blue; font-weight: bold'>MyIntClass inst</span>); </pre> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > #include "Win32Project1.h" <span style='color: blue; font-weight: bold'>void Func1(MyIntClass inst)</span> { inst.Print(); } </pre> <br /> 콘솔 프로젝트에서는 다음과 같이 사용할 수 있겠군요.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > #include "stdafx.h" #include "../Win32Project1/Win32Project1.h" #pragma comment(lib, "..//Out//Win32Project1.lib") int main() { MyIntClass inst(6, L"test"); Func1(inst); return 0; } </pre> <br /> 이렇게 변경하고 실행하면... 역시 이번에도 아무런 문제없이 잘 됩니다.<br /> <br /> <hr style='width: 50%' /> <a name='crt_conflict'></a> <br /> 그런데, 이전 글이 잠깐 생각나는군요. ^^<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > VirtualAlloc, HeapAlloc, GlobalAlloc, LocalAlloc, malloc, new의 차이점 ; <a target='tab' href='http://www.sysnet.pe.kr/2/0/11152'>http://www.sysnet.pe.kr/2/0/11152</a> </pre> <br /> DLL에서 할당한 메모리는 반드시 DLL에서 해제하는 것이 좋다고 했습니다. 그런데, 이 원칙이 깨지는 것이 바로 위에서 정의했던 (new 할당을 정의한 복사 생성자를 가진) template 클래스입니다.<br /> <br /> 문제를 재현하기 위해, 위에서 만든 DLL 프로젝트의 "Platform Toolset"을 "Visual Studio 2013 - Windows XP (v120_xp)"로 설정하고 EXE 콘솔 프로젝트는 "Visual Studio 2015 (v140)"로 설정합니다. 이렇게 바꾼 후 실행하면 이젠 다음과 같은 유형들의 예외 상자가 뜹니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Debug Assertion Failed! Program: ...\ConsoleApplication1.exe File: f:\dd\vctools\crt\crtw32\misc\dbgdel.cpp Line: 52 Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) </pre> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Debug Assertion Failed! Program: ...\ConsoleApplication1.exe File: minkernel\crts\ucrt\src\appcrt\heap\debug_heap.cpp Line: 908 Expression: is_block_type_valid(header->_block_use) </pre> <br /> 또는, DLL 프로젝트와 EXE 프로젝트를 "Visual Studio 2015 (v140)"로 맞춰도 DLL은 Debug로, EXE는 Release 모드로 컴파일 후 실행해도 예외가 발생합니다.<br /> <br /> 이유는 간단합니다. Release 프로젝트로 빌드한 EXE에서 다음과 같이 template 클래스를 DLL Export 함수에 전달하면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > int main() { MyIntClass inst(6, L"test"); Func1(inst); return 0; } </pre> <br /> Func1의 인자 타입이 MyIntClass이므로,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > WIN32PROJECT1_API void Func1(MyIntClass inst); </pre> <br /> 복사되어 전달합니다. 이때 복사 생성자의 new가 실행되고, 이것은 Release 모드의 MSVCRT dll과 링크되어 컴파일된 것입니다. 반면, DLL 측에서는,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > void Func1(MyIntClass inst) { inst.Print(); } // scope를 벗어나는 시점에 inst.~MyClass() 소멸자 실행 </pre> <br /> 복사 생성자로 새롭게 만들어진 MyIntClass 인스턴스를 함수가 끝나는 시점에 inst.~MyClass() 소멸자를 부르게 되지만, 이때의 delete는 Debug 모드의 MSVCRT dll과 링크된 코드가 실행됩니다. 이때의 불일치로 인해 예외가 발생하는 것입니다.<br /> <br /> <hr style='width: 50%' /> <br /> 그렇다면 template 클래스인 경우 어떻게 해야 하는 걸까요? 문제는 new/delete 호출 위치의 불일치이므로 이런 경우 Func1을 전달할 때 new가 발생하지 않도록 참조 인자를 받도록 하면 됩니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > WIN32PROJECT1_API void Func1(MyIntClass &inst); void Func1(MyIntClass &inst) { inst.Print(); } </pre> <br /> 그럼 호출 측에서 메모리 할당을 하지 않고 참조 주소 자체를 넘기므로 Func1 함수 호출이 끝나는 시점에 inst.~MyClass()가 호출되지 않으므로 문제가 없습니다.<br /> <br /> 그런데, 반환값으로 MyIntClass를 갖는 함수는 어떻게 해야 할까요?<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > WIN32PROJECT1_API MyIntClass Func2(); <span style='color: blue; font-weight: bold'>MyIntClass</span> Func2() { MyIntClass inst(5, L"test2"); return inst; } WIN32PROJECT1_API MyIntClass &Func3(); <span style='color: blue; font-weight: bold'>MyIntClass &</span>Func3() { MyIntClass inst(4, L"test4"); return inst; } </pre> <br /> Func2()를 호출하면, new는 DLL에서 delete는 다시 EXE에서 발생하므로 문제가 발생합니다. 참조 값으로 바꾼 Func3()은 어떨까요? Func3()을 벗어나면서 inst.~MyIntClass()가 호출되므로 이미 소멸된 객체가 되고 그것의 참조 값이 반환되었으므로 역시 문제가 됩니다.<br /> <br /> 그럼, 다음과 같이 바꾸면 어떨까요?<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > WIN32PROJECT1_API void Func5(<span style='color: blue; font-weight: bold'>MyIntClass &inst</span>); void Func5(MyIntClass &inst) { MyIntClass inst2(5, L"test2"); <span style='color: blue; font-weight: bold'>inst = inst2; // 기본 대입 연산자 실행</span> } </pre> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > MyIntClass inst; <span style='color: blue; font-weight: bold'>Func5(inst);</span> inst.Print(); </pre> <br /> 위와 같이 하면, inst = inst2 코드에서 기본 대입 연산자가 실행되는데 이는 다음과 같은 코드와 동일한 역할을 합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > MyClass& operator = (const MyClass &obj) { _a = obj._a; _pName = obj._pName; return *this; } </pre> <br /> 따라서, Func5는 scope을 벗어나자마자 inst2.~MyIntClass 소멸자가 실행되고 참조 값에 채워진 inst는 이미 해제된 메모리의 _pName을 소유하게 되므로 이후 호출 측에서 inst.~MyIntClass 소멸자가 호출되면서 문제가 발생합니다. (이 문제는 기본 복사 생성자를 재정의하지 않았을 때와 동일한 것입니다.)<br /> <br /> 그렇다면 기본 대입 연산자를 다음과 같이 재정의 해주면 어떻게 될까요?<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > MyClass& operator = (const MyClass &obj) { _a = obj._a; SetName(obj._pName); return *this; } </pre> <br /> 이렇게 해도 마찬가지 문제가 발생합니다. 대입 연산자가 실행되는 위치는 DLL이고, 참조 변수가 해제되는 곳은 EXE이기 때문에 링크된 MSVCRT DLL의 종류가 달라집니다.<br /> <br /> <hr style='width: 50%' /> <br /> 결국 반환값이 new를 소유한 template 클래스라면 답이 없습니다. 이런 경우에는 포인터를 쓰는 것이 좋습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > WIN32PROJECT1_API MyIntClass *AllocFunc(); MyIntClass *AllocFunc() { MyIntClass *pInst = new MyIntClass(5, L"test2"); return pInst; } WIN32PROJECT1_API void FreeFunc(MyIntClass *pInst); void FreeFunc(MyIntClass *pInst) { delete pInst; } </pre> <br /> 사용은 이렇게 바뀝니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > MyIntClass *pInst = AllocFunc(); pInst->Print(); FreeFunc(pInst); </pre> <br /> 물론, 이렇게 바꿨다고 해서 모든 문제가 해결된 것은 아닙니다. 위에서 보는 바와 같이 DLL과 EXE는 각자 버전의 template 소스 코드 파일을 가지고 빌드되었으므로 나중에 template 클래스 내부에 멤버 변수를 추가하는 등의 변화가 발생하면 메모리 구조가 바뀌게 됩니다. 이 때문에, template 클래스를 공통 소스 코드로 사용하는 모든 프로젝트를 다시 빌드해야 합니다.<br /> <br /> 이래저래, template 클래스 파일은 DLL로 분리된 프로젝트에서 export 함수의 인자/반환값으로 쓰는 것이 바람직하지 않게 되는 이유가 됩니다.<br /> <br /> (<a target='tab' href='https://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=1110&boardid=331301885'>첨부 파일은 이 글의 예제 코드를 포함</a>합니다.)<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
1750
(왼쪽의 숫자를 입력해야 합니다.)