简体   繁体   English

如何在Android上的C ++构造函数中失败

[英]How to fail in a C++ constructor on Android

I have a constructor in some C++ Android NDK code which is used in a larger Android project. 我在一些C ++ Android NDK代码中有一个构造函数,该代码在较大的Android项目中使用。 This constructor was missing some simple bounds checks on some parameters, which I've added. 该构造函数缺少对某些参数的简单边界检查,这是我添加的。 If they are invalid, object initialization doesn't make sense. 如果它们无效,则对象初始化没有意义。 Unfortunately, it seems exceptions are not supported in the NDK . 不幸的是, NDK似乎不支持例外。 Returning NULL isn't accepted by the compiler either(I get an error as -Wreturn-type is enabled), and it seems wrong anyway. 返回NULL也不被编译器接受(由于启用了-Wreturn-type我得到了一个错误),无论如何似乎还是错误的。

This answer provides an overview of other ways of signalling failure if exceptions aren't an option, but as they are all quite hacky. 此答案概述了如果不是不可选项的话,则可以通过其他方式来指示失败的信号,但是它们都是很容易破解的。 Since the android NDK doesn't provide exceptions, I thought it might provide some other method. 由于android NDK不提供异常,因此我认为它可能提供其他方法。 Is that the case, or do I have to resort to something hacky? 是这种情况,还是我不得不求助于某些骇人听闻的东西?

From your link: 从您的链接:

The default provided gcc version provided with the android ndk does not support exceptions. android ndk提供的默认提供的gcc版本不支持例外。

That answer is really out of date. 这个答案真的过时了。 Exceptions are perfectly supported in the latest ndk (r16b). 最新的ndk (r16b)完全支持例外。

Since the object is completely invalid if the file can't be opened, one option might be to use a Factory Method Pattern and something similar to a NullObject pattern. 由于如果无法打开文件,则对象完全无效,因此一种选择可能是使用Factory Method Pattern和类似于NullObject模式的东西。

(However, instead of calling it "NullObject", I suggest using "InvalidObject" or "IOErrorObject".) (但是,我建议不要使用“ InvalidObject”或“ IOErrorObject”,而不是将其称为“ NullObject”。)

In this way, you always get back a valid object, regardless of the constructor call which may fail. 这样,无论构造函数调用可能失败,您总是会取回有效对象。 A side benefit is that this technique can also simplify your calling code, as it helps avoid null checks. 另一个好处是,该技术还可以简化调用代码,因为它有助于避免空检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM