Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

Visual C++ 컴파일 오류 - Cannot use __try in functions that require object unwinding

"Cannot use __try in functions that require object unwinding" 오류에 대해 MSDN에 다음과 같은 설명이 있습니다.

Compiler Error C2712
; https://docs.microsoft.com/en-us/cpp/error-messages/compiler-errors-2/compiler-error-c2712

위의 내용을 간단한 예제들과 함께 살펴볼까요? ^^

우선, 소멸자가 없는 클래스를 메서드에 포함한 후 __try/__finally를 사용하면 아무런 이상이 없습니다.

class CTestClassWithoutDtor
{
public:
    CTestClassWithoutDtor() { }
};

void CTest::UseTestClassWithoutDtor()
{
    CTestClassWithoutDtor dtor;
    __try
    {

    }
    __finally
    {

    }
}

하지만, __try/__finally를 포함한 메서드에 소멸자가 있는 클래스를 사용하는 경우에는 C2712 오류가 발생합니다.

class CTestClassWithDtor
{
public:
    CTestClassWithDtor() { }
    ~CTestClassWithDtor() { }
};

void CTest::UseTestClassWithDtor()
{
    CTestClassWithDtor dtor; // error C2712 : Cannot use __try in functions that require object unwinding
    __try
    {

    }
    __finally
    {

    }
}

이는 포인터로 사용해도 마찬가지입니다.

void CTest::CreateTestClassWithDtor()
{
    CTestClassWithDtor *pDtor = new CTestClassWithDtor(); // error C2712 : Cannot use __try in functions that require object unwinding

    __try
    {

    }
    __finally
    {

    }
}

가장 이상적인 해결책은 물론 소멸자를 가진 클래스를 사용하지 않는 것입니다. 하지만, 이게 말처럼 쉬운 것이 아닙니다. 다 써야할 상황이 되니 쓰고 있는 거니까요.

대신, 생성을 우회하면 해결할 수 있습니다. 즉, new 했던 것을 다음과 같이 별도의 함수로 빼서 처리하면 됩니다.

CTestClassWithoutDtor *CTest::ClassWithoutDtorFactory() 
{ 
    return new CTestClassWithoutDtor(); 
}

void CTest::CreateTestClassWithoutDtor()
{
    // CTestClassWithoutDtor *pDtor = new CTestClassWithoutDtor();

    CTestClassWithoutDtor *pDtor = ClassWithoutDtorFactory();

    __try
    {

    }
    __finally
    {

    }
}




그 외에 STL 라이브러리에서 제공되는 클래스를 무심코 사용하다 보면 이렇게 C2712 오류가 발생합니다.

// error C2712 : Cannot use __try in functions that require object unwinding
void CTest::OutputString(wstring txt)
{
    __try
    {

    }
    __finally
    {

    }
}

왜냐하면, wstring같은 클래스들이 기본적으로 소멸자를 정의하고 있기 때문입니다. 이렇게 함수의 인자로 전달하는 경우는 포인터로 전달하면 오류를 우회할 수 있습니다.

void CTest::OutputString2(wstring *pTxt)
{
    __try
    {

    }
    __finally
    {

    }
}

아니면, 인스턴스가 스택상에 생성되지 않도록 참조형으로 전달하는 것도 가능합니다.

void CTest::OutputString(wstring &txt)
{
    __try
    {

    }
    __finally
    {

    }
}

대충... 감이 오시죠? ^^

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




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







[최초 등록일: ]
[최종 수정일: 7/17/2021]

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

비밀번호

댓글 작성자
 



2014-08-12 01시36분
아래의 글에 Visual C++ 예외와 관련해 "Enable C++ Exceptions" 옵션을 잘 설명해 주고 있으니 참고하세요. ^^

try~catch 와 __try~__except 의 차이점
; http://kuaaan.tistory.com/435
정성태

... 31  32  33  34  35  36  37  38  39  40  41  42  [43]  44  45  ...
NoWriterDateCnt.TitleFile(s)
12558정성태3/10/20219048Windows: 192. Power Automate Desktop (Preview) 소개 - Bitvise SSH Client 제어 [1]
12557정성태3/10/20217722Windows: 191. 탐색기의 보안 탭에 있는 "Object name" 경로에 LEFT-TO-RIGHT EMBEDDING 제어 문자가 포함되는 문제
12556정성태3/9/20216979오류 유형: 703. PowerShell ISE의 Debug / Toggle Breakpoint 메뉴가 비활성 상태인 경우
12555정성태3/8/20219039Windows: 190. C# - 레지스트리에 등록된 DigitalProductId로부터 라이선스 키(Product Key)를 알아내는 방법파일 다운로드2
12554정성태3/8/20218846.NET Framework: 1027. 닷넷 응용 프로그램을 위한 PDB 옵션 - full, pdbonly, portable, embedded
12553정성태3/5/20219303개발 환경 구성: 548. 기존 .NET Framework 프로젝트를 .NET Core/5+ 용으로 변환해 주는 upgrade-assistant, try-convert 도구 소개 [4]
12552정성태3/5/20218572개발 환경 구성: 547. github workflow/actions에서 Visual Studio Marketplace 패키지 등록하는 방법
12551정성태3/5/20217486오류 유형: 702. 비주얼 스튜디오 - The 'CascadePackage' package did not load correctly. (2)
12550정성태3/5/20217149오류 유형: 701. Live Share 1.0.3713.0 버전을 1.0.3884.0으로 업데이트 이후 ContactServiceModelPackage 오류 발생하는 문제
12549정성태3/4/20217663오류 유형: 700. VsixPublisher를 이용한 등록 시 다양한 오류 유형 해결책
12548정성태3/4/20218410개발 환경 구성: 546. github workflow/actions에서 nuget 패키지 등록하는 방법
12547정성태3/3/20218954오류 유형: 699. 비주얼 스튜디오 - The 'CascadePackage' package did not load correctly.
12546정성태3/3/20218559개발 환경 구성: 545. github workflow/actions에서 빌드시 snk 파일 다루는 방법 - Encrypted secrets
12545정성태3/2/202111288.NET Framework: 1026. 닷넷 5에 추가된 POH (Pinned Object Heap) [10]
12544정성태2/26/202111513.NET Framework: 1025. C# - Control의 Invalidate, Update, Refresh 차이점 [2]
12543정성태2/26/20219852VS.NET IDE: 158. C# - 디자인 타임(design-time)과 런타임(runtime)의 코드 실행 구분
12542정성태2/20/202112206개발 환경 구성: 544. github repo의 Release 활성화 및 Actions를 이용한 자동화 방법 [1]
12541정성태2/18/20219421개발 환경 구성: 543. 애저듣보잡 - Github Workflow/Actions 소개
12540정성태2/17/20219734.NET Framework: 1024. C# - Win32 API에 대한 P/Invoke를 대신하는 Microsoft.Windows.CsWin32 패키지
12539정성태2/16/20219647Windows: 189. WM_TIMER의 동작 방식 개요파일 다운로드1
12538정성태2/15/202110065.NET Framework: 1023. C# - GC 힙이 아닌 Native 힙에 인스턴스 생성 - 0SuperComicLib.LowLevel 라이브러리 소개 [2]
12537정성태2/11/202111106.NET Framework: 1022. UI 요소의 접근은 반드시 그 UI를 만든 스레드에서! - 두 번째 이야기 [2]
12536정성태2/9/202110097개발 환경 구성: 542. BDP(Bandwidth-delay product)와 TCP Receive Window
12535정성태2/9/20219205개발 환경 구성: 541. Wireshark로 확인하는 LSO(Large Send Offload), RSC(Receive Segment Coalescing) 옵션
12534정성태2/8/20219791개발 환경 구성: 540. Wireshark + C/C++로 확인하는 TCP 연결에서의 closesocket 동작 [1]파일 다운로드1
12533정성태2/8/20219436개발 환경 구성: 539. Wireshark + C/C++로 확인하는 TCP 연결에서의 shutdown 동작파일 다운로드1
... 31  32  33  34  35  36  37  38  39  40  41  42  [43]  44  45  ...