简体   繁体   中英

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. 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 . Returning NULL isn't accepted by the compiler either(I get an error as -Wreturn-type is enabled), and it seems wrong anyway.

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. 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.

That answer is really out of date. Exceptions are perfectly supported in the latest 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.

(However, instead of calling it "NullObject", I suggest using "InvalidObject" or "IOErrorObject".)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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