'Hazelcast Client Imap issues while using get() function - C++
Is there a way to know the data type before of a hazelcat key before getting the key in Hazelcast 5.0 or later versions?
Specifically, my C++ code is:
hazelcast::client::imap* mapInstance = hz->get_map("MapName").get().get();;
boost::optional<bool> v;
try{
v = mapInstance->get<std::string, bool>("key2get").get();
}
catch (...) {
//print something
}
If the hazelcast key to get is a boolean, the code works perfectly. Otherwise (for example, the tag is a double), the code cannot handle the try-catch routine and crash. A pop-up windows message appears reporting: "Abort()"
Thank you in advance for your help.
Solution 1:[1]
I just realized in your code sample that you are not using the shared_ptr properly at line hazelcast::client::imap* mapInstance = hz.get_map("MapName").get().get();
You get the raw pointer of the temporary shared_ptr which may become invalid as soon as you go to the next line. Can you please change it with: auto mapInstance = hz.get_map("MapName").get();
This is most probably the reason for the abort. Normally, you should be successfully catching the exception with catch(...)
and it should not cause abort.
The C++ API is strongly typed meaning that you require to provide the type you expect on the method template parameter. However, we have a solution for handling these situations where you may not know the data type before hand or the hazelcast data structure may have mixed types in the values. For these you can use the special type typed_data
. This special type allows you to access the type information and make runtime decisions based on the received type. You do not need to use exception handling. Here is an example code (Just submitted a PR for a code sample here as well):
using namespace hazelcast::client;
auto hz = hazelcast::new_client().get();
auto map = hz.get_map("map").get();
boost::optional<typed_data> the_value = map->get<std::string, typed_data>("key").get();
if (the_value) {
std::cout << "value type id is: " << the_value->get_type() << std::endl;
if (the_value->get_type().type_id == serialization::pimpl::serialization_constants::CONSTANT_TYPE_BOOLEAN) {
// we know for sure that the value is of type `bool` and we can get it with no exception
bool value = *the_value->get<bool>();
std::cout << "value is: " << value << std::endl;
}
} else {
std::cout << "value is not set" << std::endl;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |