在Android平台上,C++的new和new[]操作符会抛出std::bad_alloc异常吗?

8

当尝试分配内存失败时,是否会抛出任何异常?

我最近才了解到Android支持异常。


1
你为什么加了jni标签?我的问题不是关于jni的。 - Anton
2个回答

4
我下载了NDK并在文档文件夹中找到了CPLUSPLUS-SUPPORT.HTML。

I. C++ Exceptions support:

The NDK toolchain supports C++ exceptions, since NDK r5, however all C++ sources are compiled with -fno-exceptions support by default, for compatibility reasons with previous releases.

To enable it, use the '-fexceptions' C++ compiler flag. This can be done by adding the following to every module definition in your Android.mk:

LOCAL_CPPFLAGS += -fexceptions

More simply, add a single line to your Application.mk, the setting will automatically apply to all your project's NDK modules:

APP_CPPFLAGS += -fexceptions

NOTE: The obsolete "arm-eabi-4.4.0" toolchain provided for backwards compatibility with this NDK does not support exceptions!

看起来支持异常,只要应用程序使用“-fexceptions”编译。因此,我的理解是使用“-fexceptions”编译的代码将在内存分配失败时抛出std::bad_alloc异常。


0

我原本认为Android不支持异常。如果最近有所改变,您能否发布参考文章的链接?我印象中,在Android上使用new运算符进行分配失败将返回空指针。

在这种情况下,如果您在代码中使用(nothrow),则应遵守其默认分配行为,并获得与Android上预期相同的结果。

http://www.cplusplus.com/reference/std/new/nothrow/


我实际上记不清了,但是当我搜索时发现了这个网址: http://www.crystax.net/android/ndk-r5.php - Anton
啊,那似乎是谷歌 NDK 的自制实现,而谷歌 NDK 默认情况下是不带异常编译的。您需要重新编译整个 NDK 并加上 -fexceptions 才能启用它们。但是我非常担心它对 STL 和标准 C++ 异常的支持程度。我仍然建议避免使用异常,而是使用 (nothrow),因为 Android 实际上并没有考虑异常。 - AJG85
好的,我已经下载了ndk并找到了相关文档。不幸的是,我不能回答自己的问题,但据我所知,对于使用-fexceptions编译的代码,支持异常,而无需重新编译整个ndk。但STL实现是使用-fnoexceptions编译的。这对我来说都是好消息,因为我有现有的代码希望移植到Android上。 - Anton
你可以回答自己的问题...这里支持自学和分享。毕竟,有时候最好的答案是你自己找到的。 - AJG85

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接