Microsoft MVP성태의 닷넷 이야기
VC++: 108. DLL에 정의된 C++ template 클래스의 복사 생성자 문제 [링크 복사], [링크+제목 복사],
조회: 28993
글쓴 사람
정성태 (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)
13641정성태6/11/20248673Linux: 71. Ubuntu 20.04를 22.04로 업데이트
13640정성태6/10/20248835Phone: 21. C# MAUI - Android 환경에서의 파일 다운로드(DownloadManager)
13639정성태6/8/20248443오류 유형: 906. C# MAUI - Android Emulator에서 "Waiting For Debugger"로 무한 대기
13638정성태6/8/20248526오류 유형: 905. C# MAUI - 추가한 layout XML 파일이 Resource.Layout 멤버로 나오지 않는 문제
13637정성태6/6/20248458Phone: 20. C# MAUI - 유튜브 동영상을 MediaElement로 재생하는 방법
13636정성태5/30/20248089닷넷: 2264. C# - 형식 인자로 인터페이스를 갖는 제네릭 타입으로의 형변환파일 다운로드1
13635정성태5/29/20248951Phone: 19. C# MAUI - 안드로이드 "Share" 대상으로 등록하는 방법
13634정성태5/24/20249433Phone: 18. C# MAUI - 안드로이드 플랫폼에서의 Activity 제어 [1]
13633정성태5/22/20248947스크립트: 64. 파이썬 - ASGI를 만족하는 최소한의 구현 코드
13632정성태5/20/20248573Phone: 17. C# MAUI - Android 내에 Web 서비스 호스팅
13631정성태5/19/20249328Phone: 16. C# MAUI - /Download 등의 공용 디렉터리에 접근하는 방법 [1]
13630정성태5/19/20248876닷넷: 2263. C# - Thread가 Task보다 더 빠르다는 어떤 예제(?)
13629정성태5/18/20249165개발 환경 구성: 710. Android - adb.exe를 이용한 파일 전송
13628정성태5/17/20248551개발 환경 구성: 709. Windows - WHPX(Windows Hypervisor Platform)를 이용한 Android Emulator 가속
13627정성태5/17/20248618오류 유형: 904. 파이썬 - UnicodeEncodeError: 'ascii' codec can't encode character '...' in position ...: ordinal not in range(128)
13626정성태5/15/20248883Phone: 15. C# MAUI - MediaElement Source 경로 지정 방법파일 다운로드1
13625정성태5/14/20248929닷넷: 2262. C# - Exception Filter 조건(when)을 갖는 catch 절의 IL 구조
13624정성태5/12/20248724Phone: 14. C# - MAUI에서 MediaElement 사용파일 다운로드1
13623정성태5/11/20248430닷넷: 2261. C# - 구글 OAuth의 JWT (JSON Web Tokens) 해석파일 다운로드1
13622정성태5/10/20249222닷넷: 2260. C# - Google 로그인 연동 (ASP.NET 예제)파일 다운로드1
13621정성태5/10/20248638오류 유형: 903. IISExpress - Failed to register URL "..." for site "..." application "/". Error description: Cannot create a file when that file already exists. (0x800700b7)
13620정성태5/9/20248557VS.NET IDE: 190. Visual Studio가 node.exe를 경유해 Edge.exe를 띄우는 경우
13619정성태5/7/20248874닷넷: 2259. C# - decimal 저장소의 비트 구조파일 다운로드1
13618정성태5/6/20248665닷넷: 2258. C# - double (배정도 실수) 저장소의 비트 구조파일 다운로드1
13617정성태5/5/20249472닷넷: 2257. C# - float (단정도 실수) 저장소의 비트 구조파일 다운로드1
13616정성태5/3/20248630닷넷: 2256. ASP.NET Core 웹 사이트의 HTTP/HTTPS + Dual mode Socket (IPv4/IPv6) 지원 방법파일 다운로드1
1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...