USCiLab / cereal

A C++11 library for serialization
BSD 3-Clause "New" or "Revised" License
4.24k stars 767 forks source link

Unhelpful error message when deserializing wrong type #233

Open aleaverfay opened 9 years ago

aleaverfay commented 9 years ago

I had a simple problem with some code where I was serializing a pointer to a derived class and then trying to deserialize with a pointer to the base class. Running this code threw an exception, and the error message sent me barking up the wrong tree:

"Cannot load a polymorphic type that is not default constructable and does not have a load_and_construct function"

The solution was to deserialize exactly the type that I serialized; either to serialize a pointer to the base class and then deserialize a pointer to the base class, or to serialize a pointer to the derived class and deserialize a pointer to the derived class.

AzothAmmo commented 9 years ago

I'll see if there is a way to make this more clear in either the error message or documentation.

lazylazypig commented 6 years ago

@aleaverfay Hi,l'd like to serialize a pointer to the derived class and deserialize a pointer to the base class, or inversely. have you found a solution? Thanks

aleaverfay commented 6 years ago

Yes, @lazylazypig -- usually, you don't know the type you will be deserializing, so you should deserialize it as a pointer to the base class. That means you should also serialize it as a pointer to the base class.

// serialization
std::shared_ptr< Derived > derived = std::make_shared< Derived >(arg1, arg2);
std::shared_ptr< Base > base = derived;
arc( base ); // serialize as a pointer to the base type

...
// deserialization
std::shared_ptr< Base > base;
arc( base ); // deserialize as a pointer to the base type.
lazylazypig commented 6 years ago

@aleaverfay oh, i have got it. thanks for your reply 👍