我正在阅读有关复制交换习语的内容,在一个示例中,交换方法是通过以下方式实现的:
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() { /*...*/ }
....
}
现在在 swap 方法中有一个使用 static_cast
的特殊原因。
使用这样的动态转换是否安全
Base* lb = dynamic_cast<Base*>(&lhs)
Base* rb = dynamic_cast<Base*>(&rhs)
std::swap(*lb,*rb);
最佳答案
您始终可以static_cast
到明确可见的基类。 dynamic_cast
用于相反方向 - 从基类指针/引用强制转换为可能无效的派生类。这里完全没有必要,但是,它是安全的,因为它与 static_cast
具有相同的效果。
看第3点here .
3) If
new_type
is a pointer or reference toBase
, and the type of expression is a pointer or reference toDerived
, whereBase
is a unique, accessible base class ofDerived
, the result is a pointer or reference to theBase
class subobject within theDerived
object pointed or identified by expression. (Note: an implicit cast andstatic_cast
can perform this conversion as well.)
关于c++ - 复制交换成语 - 我们可以在这里使用动态转换操作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51578397/