很简单的代码,并得到错误C2712,不明白为什么

very simple code, and getting error C2712, could not understand why

本文关键字:C2712 错误 为什么 明白 简单 代码      更新时间:2023-10-16

我有麻烦一段时间与error C2712: Cannot use __try in functions that require object unwinding,缩小问题后,我留下了一个非常非常简单的代码,我不能理解为什么它会导致这个错误。我在windows下使用Visual Studio。

我正在编译/EHa(我不使用/EHsc)

我使用__try/__except而不是try/catch的原因是因为我想捕获所有错误,并且不希望程序在任何情况下崩溃,包括例如try-catch无法捕获的除0。

#include <string>
static struct myStruct
{
    static std::string foo() {return "abc";}
};
int main ()
{
    myStruct::foo();
    __try 
    { }
    __except (true)
    { }
    return 0;
}
输出:

error C2712: Cannot use __try in functions that require object unwinding

解决方案如下:有关详细信息,请参阅编译错误C2712

#include <string>
struct myStruct
{
    static std::string foo() {return "abc";}
};
void koo()
{
    __try 
    { }
    __except (true)
    { }
}
int main ()
{
    myStruct::foo();   
    koo();
    return 0;
}

额外说明:如果没有使用struct (myStruct)的声明,则不需要static