Is it safe to use reinterpret_cast to convert std::list<Derived *> to std::list<Base *>?
class Base {
...
}
class Derived : public Base{
...
}
void func(const std::list<Base *> &list);
int main() {
std::list<Derived *> list1;
// ...
func(*reinterpret_cast<std::list<Base *> *>(&list1)); // Safe ?
}
If it's a safe cast, we don't need to copy the list, which may improve performance.
This is wrong. Even if you could reinterpret cast a
Derived*to aBase*, you cannot reinterpret cast astd::list<Derived*>to astd::list<Base*>in a meaningful, portable way. They are two unrelated types. Being instantiations of the same template does not impose any relation between them, other than being instantiations of the same template.reinterpret_castis often misunderstood as an any-to-any cast, but thats not what it is. Actually it has a rather limited set of valid use cases. For a complete list see here: https://en.cppreference.com/w/cpp/language/reinterpret_cast. Casting astd::list<Derived*>to astd::list<Base*>is not among them.Probably you do not have to copy the list in the first place. If the types are polymorphic then no copy nor cast is needed, you can use the
std::list<Base*>and the elements virtual methods. If however you do need to cast aDerived*to aBase*then you can cast the elements viadynamic_castwithout casting the whole list. Also no copy needed.