Microsoft MVP성태의 닷넷 이야기
VC++: 108. DLL에 정의된 C++ template 클래스의 복사 생성자 문제 [링크 복사], [링크+제목 복사]
조회: 22195
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 3개 있습니다.)
(시리즈 글이 4개 있습니다.)
VC++: 108. DLL에 정의된 C++ template 클래스의 복사 생성자 문제
; https://www.sysnet.pe.kr/2/0/11153

VC++: 109. DLL에서 STL 객체를 인자/반환값으로 갖는 함수를 제공할 때, 그 함수를 외부에서 사용하는 경우 비정상 종료한다면?
; https://www.sysnet.pe.kr/2/0/11154

VC++: 115. Visual Studio에서 C++ DLL을 대상으로 단위 테스트할 때 비정상 종료한다면?
; https://www.sysnet.pe.kr/2/0/11173

오류 유형: 683. Visual C++ - error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MDd_DynamicDebug'
; https://www.sysnet.pe.kr/2/0/12418




DLL에 정의된 C++ template 클래스의 복사 생성자 문제

다음의 예제 클래스를 보겠습니다.

#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 inst2(inst); // 기본 복사 생성자 호출
    inst2.Print();

    MyClass inst3 = inst;  // 기본 복사 생성자가 호출되는 또 다른 유형
    inst3.Print();

    return 0;
}

/*
출력 결과:
6
6
6
*/

C++은 사용자가 정의하지 않은 경우 다음과 같은 복사 생성자를 기본으로 제공합니다.

MyClass(const MyClass &obj)
{
    _a = obj._a;
}

그렇기 때문에 위의 소스 코드에서 출력 결과가 모두 6이 나온 것입니다. 일반적으로 기본 복사 생성자는 primitive 타입의 멤버 변수를 가진 class에게는 충분히 사용할만합니다.

문제는, 포인터 멤버 변수가 들어간 경우입니다.

class MyClass
{
    int _a = 0;
    wchar_t *_pName = nullptr;

public:
    MyClass() { }

    MyClass(int a, wchar_t *pName)
    {
        _a = a;
        SetName(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");

    inst2.Print();
    inst3.Print();

    return 0;
}

/*
출력 결과:
6, test
6, test2
6, test2
*/

보는 바와 같이, inst 변수에 대해서만 SetName으로 이름을 바꿨는데도, 그 이전에 값 복사가 이뤄졌던 inst2, inst3에 대해서도 이름이 바뀌어서 출력되고 있습니다. 왜냐하면, 이럴 때 제공되는 C++ 컴파일러의 기본 복사 생성자는 다음과 같기 때문입니다.

MyClass(const MyClass &obj)
{
    _a = obj._a;
    _pName = obj._pName;
}

그런데, 사실 MyClass에서는 소멸자 정의가 빠져있습니다. 따라서 다음과 같은 코드를 추가해야 하는데,

~MyClass()
{
    if (_pName != nullptr)
    {
        delete[] _pName;
    }
}

변경 후, 예제 코드를 실행하면 이제는 다음과 같은 예외가 발생합니다.

Debug Assertion Failed!

Program: ...s\ConsoleApplication1\Debug\ConsoleApplication1.exe
File: minkernel\crts\ucrt\src\appcrt\heap\debug_heap.cpp
Line: 904

Expression: _CrtIsValidHeapPointer(block)

이유는 간단합니다. main 함수의 scope가 벗어날 때 inst, inst2, inst3에 대해 소멸자 함수가 실행될 텐데, 한 번만 할당된 _pName 영역을 inst.~MyClass 소멸자에서 이미 해제를 한 상태에서 inst2.~MyClass, inst3.~MyClass를 통해 중복 해제를 시도하기 때문입니다.

따라서, 이렇게 포인터가 포함된 클래스를 정의한 경우에는 자연스럽게 사용자가 직접 복사 생성자를 정의해 줘야만 합니다.

#include "stdafx.h"

class 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);
    }
};

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
*/

참고로, 올바른 복사 생성자 없이 STL 컨테이너 클래스를 다음과 같은 식으로 사용해도 동일한 오류가 발생합니다.
int main()
{
    MyClass inst(6, L"test");

    vector<MyClass> v;

    v.push_back(inst); // 복사 생성자가 호출되어 vector에 추가되므로,

    return 0; // scope를 벗어나는 시점에 inst.~MyClass()와 v[0].~MyClass() 소멸자가 호출되므로!
}



자, 이제 MyClass를 별도의 DLL 프로젝트로 분리해 보겠습니다.

#pragma once

#ifdef WIN32PROJECT1_EXPORTS
#define WIN32PROJECT1_API __declspec(dllexport)
#else
#define WIN32PROJECT1_API __declspec(dllimport)
#endif

#include <string>
using namespace std;

class WIN32PROJECT1_API 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);
    }
};

그런 다음 콘솔 프로젝트를 만들어 테스트해봅니다.

#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
*/

별다른 이상 없이 잘 호출됩니다. 한번 더 변형을 해볼까요? ^^ MyClass를 export하지 않고 다음과 같이 template으로 정의한 후,

#pragma once

#ifdef WIN32PROJECT1_EXPORTS
#define WIN32PROJECT1_API __declspec(dllexport)
#else
#define WIN32PROJECT1_API __declspec(dllimport)
#endif

#include <string>
using namespace std;

template<typename T>
class MyClass
{
    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);
    }
};

typedef MyClass<int> MyIntClass;

DLL 측에서 이 클래스를 사용하는 함수를 정의해 export 시킵니다.

WIN32PROJECT1_API void Func1(MyIntClass inst);

#include "Win32Project1.h"

void Func1(MyIntClass inst)
{
    inst.Print();
}

콘솔 프로젝트에서는 다음과 같이 사용할 수 있겠군요.

#include "stdafx.h"

#include "../Win32Project1/Win32Project1.h"
#pragma comment(lib, "..//Out//Win32Project1.lib")

int main()
{
    MyIntClass inst(6, L"test");
    Func1(inst);

    return 0;
}

이렇게 변경하고 실행하면... 역시 이번에도 아무런 문제없이 잘 됩니다.



그런데, 이전 글이 잠깐 생각나는군요. ^^

VirtualAlloc, HeapAlloc, GlobalAlloc, LocalAlloc, malloc, new의 차이점
; https://www.sysnet.pe.kr/2/0/11152

DLL에서 할당한 메모리는 반드시 DLL에서 해제하는 것이 좋다고 했습니다. 그런데, 이 원칙이 깨지는 것이 바로 위에서 정의했던 (new 할당을 정의한 복사 생성자를 가진) template 클래스입니다.

문제를 재현하기 위해, 위에서 만든 DLL 프로젝트의 "Platform Toolset"을 "Visual Studio 2013 - Windows XP (v120_xp)"로 설정하고 EXE 콘솔 프로젝트는 "Visual Studio 2015 (v140)"로 설정합니다. 이렇게 바꾼 후 실행하면 이젠 다음과 같은 유형들의 예외 상자가 뜹니다.

Debug Assertion Failed!

Program: ...\ConsoleApplication1.exe
File: f:\dd\vctools\crt\crtw32\misc\dbgdel.cpp
Line: 52

Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)

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)

또는, DLL 프로젝트와 EXE 프로젝트를 "Visual Studio 2015 (v140)"로 맞춰도 DLL은 Debug로, EXE는 Release 모드로 컴파일 후 실행해도 예외가 발생합니다.

이유는 간단합니다. Release 프로젝트로 빌드한 EXE에서 다음과 같이 template 클래스를 DLL Export 함수에 전달하면,

int main()
{
    MyIntClass inst(6, L"test");
    Func1(inst);

    return 0;
}

Func1의 인자 타입이 MyIntClass이므로,

WIN32PROJECT1_API void Func1(MyIntClass inst);

복사되어 전달합니다. 이때 복사 생성자의 new가 실행되고, 이것은 Release 모드의 MSVCRT dll과 링크되어 컴파일된 것입니다. 반면, DLL 측에서는,

void Func1(MyIntClass inst)
{
    inst.Print();
} // scope를 벗어나는 시점에 inst.~MyClass() 소멸자 실행

복사 생성자로 새롭게 만들어진 MyIntClass 인스턴스를 함수가 끝나는 시점에 inst.~MyClass() 소멸자를 부르게 되지만, 이때의 delete는 Debug 모드의 MSVCRT dll과 링크된 코드가 실행됩니다. 이때의 불일치로 인해 예외가 발생하는 것입니다.



그렇다면 template 클래스인 경우 어떻게 해야 하는 걸까요? 문제는 new/delete 호출 위치의 불일치이므로 이런 경우 Func1을 전달할 때 new가 발생하지 않도록 참조 인자를 받도록 하면 됩니다.

WIN32PROJECT1_API void Func1(MyIntClass &inst);

void Func1(MyIntClass &inst)
{
    inst.Print();
}

그럼 호출 측에서 메모리 할당을 하지 않고 참조 주소 자체를 넘기므로 Func1 함수 호출이 끝나는 시점에 inst.~MyClass()가 호출되지 않으므로 문제가 없습니다.

그런데, 반환값으로 MyIntClass를 갖는 함수는 어떻게 해야 할까요?

WIN32PROJECT1_API MyIntClass Func2();

MyIntClass Func2()
{
    MyIntClass inst(5, L"test2");
    return inst;
}

WIN32PROJECT1_API MyIntClass &Func3();

MyIntClass &Func3()
{
    MyIntClass inst(4, L"test4");
    return inst;
}

Func2()를 호출하면, new는 DLL에서 delete는 다시 EXE에서 발생하므로 문제가 발생합니다. 참조 값으로 바꾼 Func3()은 어떨까요? Func3()을 벗어나면서 inst.~MyIntClass()가 호출되므로 이미 소멸된 객체가 되고 그것의 참조 값이 반환되었으므로 역시 문제가 됩니다.

그럼, 다음과 같이 바꾸면 어떨까요?

WIN32PROJECT1_API void Func5(MyIntClass &inst);

void Func5(MyIntClass &inst)
{
    MyIntClass inst2(5, L"test2");
    inst = inst2; // 기본 대입 연산자 실행
}

MyIntClass inst;
Func5(inst);
inst.Print();

위와 같이 하면, inst = inst2 코드에서 기본 대입 연산자가 실행되는데 이는 다음과 같은 코드와 동일한 역할을 합니다.

MyClass& operator = (const MyClass &obj)
{
    _a = obj._a;
    _pName = obj._pName;

    return *this;
}

따라서, Func5는 scope을 벗어나자마자 inst2.~MyIntClass 소멸자가 실행되고 참조 값에 채워진 inst는 이미 해제된 메모리의 _pName을 소유하게 되므로 이후 호출 측에서 inst.~MyIntClass 소멸자가 호출되면서 문제가 발생합니다. (이 문제는 기본 복사 생성자를 재정의하지 않았을 때와 동일한 것입니다.)

그렇다면 기본 대입 연산자를 다음과 같이 재정의 해주면 어떻게 될까요?

MyClass& operator = (const MyClass &obj)
{
    _a = obj._a;
    SetName(obj._pName);

    return *this;
}

이렇게 해도 마찬가지 문제가 발생합니다. 대입 연산자가 실행되는 위치는 DLL이고, 참조 변수가 해제되는 곳은 EXE이기 때문에 링크된 MSVCRT DLL의 종류가 달라집니다.



결국 반환값이 new를 소유한 template 클래스라면 답이 없습니다. 이런 경우에는 포인터를 쓰는 것이 좋습니다.

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;
}

사용은 이렇게 바뀝니다.

MyIntClass *pInst = AllocFunc();
pInst->Print();
FreeFunc(pInst);

물론, 이렇게 바꿨다고 해서 모든 문제가 해결된 것은 아닙니다. 위에서 보는 바와 같이 DLL과 EXE는 각자 버전의 template 소스 코드 파일을 가지고 빌드되었으므로 나중에 template 클래스 내부에 멤버 변수를 추가하는 등의 변화가 발생하면 메모리 구조가 바뀌게 됩니다. 이 때문에, template 클래스를 공통 소스 코드로 사용하는 모든 프로젝트를 다시 빌드해야 합니다.

이래저래, template 클래스 파일은 DLL로 분리된 프로젝트에서 export 함수의 인자/반환값으로 쓰는 것이 바람직하지 않게 되는 이유가 됩니다.

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 12/20/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13606정성태4/24/202444닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/2024313닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024322오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/2024505닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/2024791닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024837닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024845닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024862닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024884닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024859닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241049닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241050닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241068닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241079닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241217C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241193닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241078Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241150닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241262닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241168오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241324Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241111Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241060개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241194Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241453Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...