Skip to content

Draft: Add type erased wrapper for entities (for discussion only!)

Re. #77 (closed)

On this branch I've whipped up one possible alternative to the std::optional<std::reference_wrapper>> return type. The implementation is based on the Type Erasure pattern, but the type erased wrapper does not take ownership of the wrapped object. Instead, it wraps a std::shared_ptr to the object and converts it to a std::weak_ptr for storage.

Each access through the member functions tries to lock the weak_ptr and throws, if the object is no longer accessible.

The wrapper has some interesting properties:

  1. It can wrap any class with matching function signatures without inheritance
  2. It checks, if the wrapped object is still accessible
  3. It is a value type, so it's easy and safe to handle for the user
  4. It prohibits the user from taking permament shared ownership of the wrapped object

All of the above comes at hefty price though: it adds some runtime overhead and considerable complexity as well as implementation overhead. The main advantage over just returning a std::weak_ptr is, that the user cannot take permament shared ownership of the wrapped object.

So the question is, what's the worst that can happen when a user takes permanent shared ownership of say, an IEntity returned from IEntityRepository?

In my opinion, the added safety is just not worth the considerable overhead and complexity. I'd vote for replacing std::optional<std::reference_wrapper>> by std::weak_ptr.

Cheers Martin

Merge request reports

Loading