以编程方式确定是否启用异常
大多数 C++ 编译器允许禁用异常。有没有一种方法可以从代码中确定它,而不使用特定于编译器的预处理器宏(例如 MSVC 的 _CPPUNWIND )?最好是在编译时。
Most C++ compilers allow for exceptions to be disabled. Is there a way to determine it from the code without using compiler-specific preprocessor macros, such as _CPPUNWIND for MSVC? Ideally at compile time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
自2014 年 WG21 以来,有一个推荐要使用的宏
如果支持异常且编译器符合 C++98,则其值为 199711。其他类似的功能宏显示在此处。
Since WG21 in 2014, there is a recommended macro to use
It will have the value 199711 if exceptions are supported and the compiler conforms to C++98. Other similar feature macros are shown here.
我根本不会因为这个决定而给运行时带来负担。相反,我会构建两个库:
然后我会让我的
configure
脚本确定我们是否有异常,并像这样设置 Makefile:要确定是否有异常,您可以简单地尝试按照评论中的建议使用简单的 try/catch 块构建一个小型测试程序。
要实际构建您的库,只需编写条件代码:
然后构建两个库,一个使用
-DHAVE_EXCEPTIONS=0
,另一个使用-DHAVE_EXCEPTIONS=1
或类似的内容。这样您就没有运行时开销,并且您的客户可以使用他们喜欢的任何库。
I'd not burden the runtime with this decision at all. Instead, I'd build two libraries:
Then I'd have my
configure
script determine whether or not we have exceptions, and set the Makefile like this:To determine whether or not you have exceptions you could simply try to build a tiny test program with a trivial try/catch block as suggested in the comments.
To actually build your library, just write conditional code:
And then build two libraries, one with
-DHAVE_EXCEPTIONS=0
and one with-DHAVE_EXCEPTIONS=1
or something like that.That way you have no runtime overhead, and your clients can use whichever library they prefer.
不。异常是 C++ 的一部分。事实上,某些编译器允许您禁用它们是完全无关紧要的,并且标准不会让您检测它们是否已启用 - 就其而言,它们始终处于启用状态。如果您想了解特定于实现的行为,唯一的方法就是询问实现。
No. Exceptions are part of C++. The fact that some compilers allow you to disable them is quite irrelevant and the Standard will not provide for you to detect if they're enabled- as far as it's concerned, they're always enabled. If you want to know about implementation-specific behaviour, the only way to go is to ask the implementation.