c++ - Is it safe to convert type of a unique_ptr? -


template <class t> class foo {};  class manager {     std::unordered_map<size_t, std::unique_ptr<std::vector<void *>>> _mfoos;  public:     template <class t> void addfoo(foo<t> &foo) {         int x = typeid(t).hash_code();          // safe ? :         auto &p = *(reinterpret_cast<std::unique_ptr<std::vector<foo<t>>> *>(&_mfoos[x]));          if (p == nullptr) {             p.reset(new std::vector<foo<t>>);         }          auto &foos = *p;         foos.push_back(foo);     };      template <class t> foo<t> &getfoo(int index) {         int x = typeid(t).hash_code();         auto = _mfoos.find(x);          auto &foos = *(reinterpret_cast<std::vector<foo<t>> *>(it->second.get()));          return foos[index];     }; }; 

is safe , portable reinterpret_cast unique_ptr< t > in unique_ptr< t2 > if t , t2 2 different types ? have same size , same bit pattern ?

no.

casting between unrelated types (and different template instances unrelated types) undefined behavior according strict aliasing rule.


Comments