In C++, how to deal with NULL values in a context where we might expect a string or an integer?
Typically, the context would be when retrieving data from a database, e.g. with a LEFT JOIN where some non-existing values in some column would be represented by a NuLL value instead of the expected string or integer.
Strong casting in C++ makes this type of scenario much more difficult to deal with than with PHP.
In PHP, we can easily have a if/else switch using the === operator:
if ($va开发者_如何学编程lue === NULL) {
// No data.
} else {
// We have some valid data.
}
What would the equivalent look like in C++?
I've searched and couldn't find a C++ relevant question.
The question is valid in general. In my particular case, I am using the dbixx SQL library.
boost::optional
is a natural way to represent maybe types in c++ with strong type checking (types that could be null must be checked for null)
From http://art-blog.no-ip.info/wikipp/en/page/ref_dbixx_row :
Function
cols()
returns number of columns in the row.isnull()
returns if specific filed is null, using it's column number (starting from 1) or column name;
bool operator[]
is just syntactic sugar forisnull()
.
In your question you stated you were using dbixx, so I have linked to their documentation. This will always be specific to the library you are using.
It may sound like a general concept, but there is no general answer for C++. The language itself does not have a truly general "NULL" value that can by used with all types to distinguish from having been set to an actual value.
So the answer in any situation entirely depends on the library or whatever that you're working with and how it has been designed to indicate "NULL" values. The return values of functions used to access the data may perhaps indicate whether the data is NULL or otherwise. Or there may be something like a separate IsNull() function. Or the library may use some other different scheme. There are many possibilities.
The only possible general answer is: read the documentation of the library to find out how they specifically deal with it.
For string pointers (and object pointers in general), it's easy, they can hold 0 to show that they're null.
For integers, you have to rely on an external variable that says if the object returned is null or not. Or if you pass it as a pointer, you can use a 0 pointer like above.
精彩评论