在 CLI 中抛出 std::exception 会引发访问冲突

Throwing std::exception in CLI throws Access Violation

由于我的 C++ 代码中存在一些 C# 依赖项,我不得不使用 CLI。 在这个依赖进来之前,我写了一个异常,它继承自std::exception。每当我现在抛出这个异常时,我的程序都会因来自 ntd.dll.

的访问冲突异常而崩溃

所以我将包含异常的 header 文件放在一个新的 CLI 项目中并尝试编译它。这给了我错误,即 "exception" 不是 std 的成员。在包括 <exception> 之后,这个错误就消失了(当然),但我想知道,为什么以前没有必要这样做...... 无论如何,这是我在基本示例中的代码:

异常header:

#pragma once

#include <exception>

//Device is offline
struct E_DvcOffline : public std::exception
{
    const char * what() const throw ()
    {
        return "The Device is offline";
    }
};

主要功能:

#include <MyExceptions.hpp>
#include <iostream>

using namespace System;




int main(array<String^>^ args) {

    try {

        throw E_DvcOffline();
    }
    catch (E_DvcOffline) {

        std::cout << "Caught it" << std::endl;
        std::cin.get();
    }


}

以及我收到的异常,当代码抛出我的自定义异常时:

Not able to embed pictures yet...

提前致谢, 卡尔文

编辑

throw new E_DvcOffline(); 改为 throw E_DvcOffline();

我能够解决问题。

#pragma once
**#pragma managed(push, off)**

#include <exception>

//Device is offline
struct E_DvcOffline : public std::exception
{
    const char * what() const throw ()
    {
        return "The Device is offline";
    }
};
**#pragma managed(pop)**

改变是螺栓。 我没有搜索它,但我认为,这告诉编译器将此代码视为非托管代码,因此调用本机异常处理程序。

警告:当您在调试模式下逐步执行代码时,Visual Studio 最终会产生与之前相同的错误。否则一切正常。