当尝试分配内存失败时,是否会抛出任何异常?
我最近才了解到Android支持异常。
当尝试分配内存失败时,是否会抛出任何异常?
我最近才了解到Android支持异常。
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异常。
我原本认为Android不支持异常。如果最近有所改变,您能否发布参考文章的链接?我印象中,在Android上使用new运算符进行分配失败将返回空指针。
在这种情况下,如果您在代码中使用(nothrow)
,则应遵守其默认分配行为,并获得与Android上预期相同的结果。
-fexceptions
才能启用它们。但是我非常担心它对 STL 和标准 C++ 异常的支持程度。我仍然建议避免使用异常,而是使用 (nothrow)
,因为 Android 实际上并没有考虑异常。 - AJG85