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
정성태

1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13544정성태1/30/20242041오류 유형: 894. Microsoft.Data.SqlClient - Could not load file or assembly 'System.Security.Permissions, ...'
13543정성태1/30/20242075Windows: 254. Windows - 기본 사용 중인 5357 포트 비활성화는 방법
13542정성태1/30/20242090오류 유형: 893. Visual Studio - Web Application을 실행하지 못하는 IISExpress - 두 번째 이야기
13541정성태1/29/20242195VS.NET IDE: 188. launchSettings.json의 useSSL 옵션
13540정성태1/29/20242336Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
13539정성태1/26/20242426개발 환경 구성: 703. Visual Studio - launchSettings.json을 이용한 HTTP/HTTPS 포트 바인딩
13538정성태1/25/20242514닷넷: 2211. C# - NonGC(FOH) 영역에 .NET 개체를 생성파일 다운로드1
13537정성태1/24/20242629닷넷: 2210. C# - Native 메모리에 .NET 개체를 생성파일 다운로드1
13536정성태1/23/20242653닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
13535정성태1/22/20242556닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/20242321닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
13533정성태1/18/20242530닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현파일 다운로드1
13532정성태1/17/20242437닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/20242392닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242267닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20242153닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242305Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20242221오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242310닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242275오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242347오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20242154오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/20242293닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/20242349닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20242129오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
13519정성태1/10/20242184닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...