Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

registerSharedPointer to getSharedPointer with same input id not working #711

Open
Belfer opened this issue Aug 26, 2021 · 0 comments
Open

Comments

@Belfer
Copy link

Belfer commented Aug 26, 2021

So I'm trying to overcome the problem of dependency injection by adding a smart pointer to the archive with contains the dependencies via registerSharedPointer. Then, on the serialization functions, I can get this pointer by calling getSharedPointer.

This worked well in my first attempt at registering the pointer to the id 1 (0 can't be used as per getSharedPointer impl), to make this a bit more robust I want to use type_index on the registered type so I don't have to keep a look-up table for id -> pointer extraction. The following is the wrapper code for this:

  namespace Serial
  {
        template <typename Archive, typename TPtr>
        void RegisterPointer(Archive& archive, TPtr* ptr)
        {
              std::size_t id = std::type_index(typeid(TPtr)).hash_code();
              archive.registerSharedPointer(id, std::shared_ptr<TPtr>(ptr));
        }

        template <typename Archive, typename TPtr>
        void GetPointer(Archive& archive, TPtr* ptr)
        {
              std::size_t id = std::type_index(typeid(TPtr)).hash_code();
              ptr = static_cast<TPtr*>(archive.getSharedPointer(id).get());
        }
  }

The problem with this is that first, the cereal id expects a std::uint32_t which will truncate the std::size_t.

Secondly, in the registerSharedPointer there is this line of code which will change the input id:
std::uint32_t const stripped_id = id & ~detail::msb_32bit;

This would be ok(ish) if it also did it on getSharedPointer, however, it does not, which causes the function to fail and throw an exception.

My main concern is the stripping of the id, which seems rather unnecessary, but I could just be missing some very important detail as to why it's there. I tested by changing to std::size_t and not stripping the id and everything worked fine still.

Would be nice to hear your ideas! And possibly some design changes?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant