Skip to content

败犬日报 2025-01-09

1. 切片

下面代码可能会有警告 Slicing derived object "d" by converting class type "Derived" to class type "Base".

cpp
class Base {
   private:
    int x;

   protected:
    Base(Base const& b) : x(b.x) {}
};

class Derived : public Base {
   private:
    int y;

   public:
    Derived(Derived const& d) : Base(d), y(d.y) {}  // Base(d) 发生了切片
};

切片是指将派生类转换到基类的过程。上面例子里 Derived 类的拷贝构造函数中,将 Derived 引用转换为 Base 引用就会发生切片。

警告可以通过显式类型转换来消除:

cpp
Derived(Derived const& d) : Base(static_cast<Base const&>(d)), y(d.y) {}

但是这里的切片发生在构造函数中,显得有点奇怪,应该是检查工具的错报。

推荐阅读:https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es63-dont-slice