dimanche 30 octobre 2016

C++ reinterpret_cast of std::shared_ref to optimize

You have two classes Animal and Dog (where Dog inherits from Animal), and you have a situation where you are often expecting an animal but are sending an instance of a dog. In my particular case, I am often casting a strong pointer (std::shared_ptr<Dog>) to an animal-expecting function (std::shared_ptr<Animal>).

If we accept that we can make the function parameter a reference (std::shared_ptr<Animal>&, avoiding arguments as to why you should not have strong pointers as reference parameters because of concerns of changing ownership with threads), I assume we would be safe memory-wise to cast a std::shared_ptr<Dog> dog using reinterpret_cast<Animal>(dog), right?

And if so, what could come up other than threading issues; such as that of the reference counting variety?

To be clear, the intent is to have a solution that would be used in many instances, where casting once isn't really a viable solution. It's more the issue that there are many objects that would have to be cast.

Aucun commentaire:

Enregistrer un commentaire