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

标签 c++ visual-c++ visual-studio-2013 visual-studio-2015

我在 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/

相关文章:

java - C 错误的 JNI 访问对象数组

c++ - 用于 C++ 的 Win32 CRITICAL_SECTION 的轻量级跨平台替代品?

java - 相当于C#中的java包

c++ - 尝试编译我的wxWidgets程序时出现 “is_enum not declared in this scope”错误

c++ - 一般情况下 typedef 可以用于 vector 吗?

android - 如何在 native Android 应用程序中获取显示指标

visual-c++ - Visual Studio 2013 编辑并继续不起作用

c - 如何使用 VC++ 编译器刷新 .C 程序中的标准输入设备?

c# - 列表框无法显示子类变量

c++ - 错误 C2661 : 'node::node' : no overloaded function takes 3 arguments