gpt4 book ai didi

c++ - std::uncaught_exception 不能跨 DLL 边界工作

转载 作者:太空狗 更新时间:2023-10-29 20:54:41 25 4
gpt4 key购买 nike

我在 DLL 中有一个类,它有一个析构函数来检查 std::uncaught_exception()。如果在可执行文件的 try/catch block 中使用,如果抛出异常,它不会说 true。

下面是一些示例代码:库.h:

#pragma once

class __declspec(dllexport) C final
{
public:
~C();
};

lib.cpp:

#include "lib.h"
#include <iostream>
#include <exception>

C::~C()
{
std::cout << "C says: Uncaught: " << (std::uncaught_exception() ? "yes" : "no") << std::endl;
}

主要.cpp:

#include "lib.h"
#include <iostream>
#include <exception>

class D final
{
public:
~D()
{
std::cout << "D says: Uncaught: " << (std::uncaught_exception() ? "yes" : "no") << std::endl;
}
};


int main(int argc, char **argv)
{
try
{
C c;
D d;
throw 88;
}
catch (int a)
{
std::cout << "Code: " << a << std::endl;
}
{
C c;
D d;
}
return 0;
}

并使用以下方法构建一切:

cl.exe lib.cpp /EHsc /LD /c /Fo:lib.obj
link.exe lib.obj /incremental:no /fixed:no /DLL
cl.exe main.cpp /EHsc /LD /c /Fo:main.obj
link.exe main.obj /incremental:no /fixed:no lib.lib

在 Visual Studio 2015 和 Visual Studio 2013 x64 和 x86 上我得到了结果:

D says: Uncaught: yes
C says: Uncaught: no
Code: 88
D says: Uncaught: no
C says: Uncaught: no

我希望第二行是

C says: Uncaught: yes

所以 DLL 中的类没有看到有异常导致堆栈展开导致它的析构函数被调用。但是直接位于内部类的类看到了。

是否有任何链接器/编译器标志可以使它按预期工作?

最佳答案

使用/MD 动态运行时编译器选项。

没有一个,主要的可执行文件和每个 DLL 都有自己的运行时拷贝,每个模块的所有内部状态都被复制。

关于c++ - std::uncaught_exception 不能跨 DLL 边界工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38348128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com