c++ - Is such a downcast safe? -


suppose have following code:

#include <memory> #include <vector>  struct basecomponent {     template <typename t>     t * as()     {         return static_cast<t*>(this);     }      virtual ~basecomponent() {} };  template <typename t> struct component : public basecomponent {     virtual ~component() {} };  struct positioncomponent : public component<positioncomponent> {     float x, y, z;      virtual ~positioncomponent() {} };  int main() {     std::vector<std::unique_ptr<basecomponent>> mcomponents;     mcomponents.emplace_back(new positioncomponent);      auto *pos = mcomponents[0]->as<positioncomponent>();     pos->x = 1337;      return 0; } 

in t * as() method, should use static_cast or dynamic_cast? there times when the conversion fail? need dynamic_cast instead?

    auto *ptr = dynamic_cast<t*>(this);      if(ptr == nullptr)         throw std::runtime_error("d'oh!");      return ptr; 

the code present correct , formed, cast in general not safe. if actual object not positioncomponent, compiler gladly assume , causing undefined behavior.

if replace cast dynamic_cast, compiler generate code @ runtime verifies conversion valid.

the real question why need this. there reasons, more not use of casts indication of issues design. reconsider whether can better (i.e. redesign code don't need go explicitly converting types)


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -