I was reading about the copy swap idiom and in an example the swap method was implemented in the following way:
class Derived : public Base
{
public:
std::string title = "";
details *detail = nullptr;
void swap(Derived& lhs, Derived& rhs)
{
using std::swap;
Base& lb = static_cast<Base&>(lhs);
Base& rb = static_cast<Base&>(rhs);
std::swap(lb,rb);
std::swap(lhs.title, rhs.title);
std::swap(lhs.detail, rhs.detail);
}
//Regular Contructor
Derived() { /*...*/ }
....
}
Now in the swap method is there a special reason that static_cast
was used.
Will it be safe to use a dynamic cast like this
Base* lb = dynamic_cast<Base*>(&lhs)
Base* rb = dynamic_cast<Base*>(&rhs)
std::swap(*lb,*rb);