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
{
}
}
대충... 감이 오시죠? ^^
(
첨부한 파일은 위의 예제 코드를 포함합니다.)
[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]