c++ - 复制交换成语 - 我们可以在这里使用动态转换操作吗?

标签 c++

我正在阅读有关复制交换习语的内容,在一个示例中,交换方法是通过以下方式实现的:

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 to Base, and the type of expression is a pointer or reference to Derived, where Base is a unique, accessible base class of Derived, the result is a pointer or reference to the Base class subobject within the Derived object pointed or identified by expression. (Note: an implicit cast and static_cast can perform this conversion as well.)

关于c++ - 复制交换成语 - 我们可以在这里使用动态转换操作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51578397/

相关文章:

c++ - 为什么下面的程序在不使用互斥量时不混合输出?

c++ - 迷宫表示帮助

c++ - 结构 (C) 中的 malloc 错误

c++ - 在 Windows 上使用 C++ 中的 Select 函数进行轮询

c++ - Win32 : Storing Multi-Line Text in a Buffer

c++ - 在 C++ 中将具有 unique_ptr 的对象插入 vector

C++ 预处理器#define-ing 一个关键字。是否符合标准?

C++ 在带有右值缓冲区的 ostream 中使用 snprintf,格式是否正确?

c++ - 是否可以在隐藏窗口模拟鼠标移动和鼠标点击?

c++ - 有什么合理的理由使一元运算符 & 过载?