In our code we sometimes return a non-const reference to the object for chaining method calls. For example:
registry.GetComponent(entityID).GetParams().GetTuners().SetWidth(50)
Sometimes in our reviews, we receive code that stores the reference and does something with it, which we forbid.
auto& comp = registry.GetComponent(2);
// ... do something with component
// ... with our pooling, comp could invalid at any point
We catch it most of the time, but sometimes it goes through and results in hard to find crashes. We tried implementing a wrapper (which stores private reference internally) that is returned instead of the references and this wrapper is non-copyable. Since the dot operator cannot be overloaded (that would have been perfect in this case), we overloaded the () operator instead.
So now we have
// all GetXXXXX are now const ref
// registry.GetComponent(entityID).GetParams().GetTuners().SetWidth(50)
registry.UpdateComponent(entityID)().UpdateParams()().UpdateTuners()().SetWidth(50)
// this is still possible, but easier to catch in code reviews
auto comp = registry.UpdateComponent(entityID);
comp().UpdateParams()().UpdateTuners()().SetWidth(50);
Ugly, but much more visible in code reviews, and if stored locally and then used, it's very easy to spot in code reviews as well.
Is it possible to return a reference to the modifiable object but prevent it from being stored OR a different pattern that allows us to safely modify nested objects.
Notes: The above reflect our code somewhat, but are very contrived examples. I hope the intent of the question is clear.