TL;DR: You should not inherit from a publicly copyable/movable class.
实际上,在编译时可以防止对象切片:在此上下文中,基础对象不应该是可复制的 .
案例1:抽象基础
如果基础是抽象的,那么它就无法实例化,因此您无法体验切片 .
案例2:具体基础
如果基础不是抽象的,则可以复制它(默认情况下) . 你有两个选择:
完全阻止复制
仅允许儿童复制
注意:在C 11中,移动操作会导致相同的问题 .
// C++ 03, prevent copy
class Base {
public:
private:
Base(Base const&);
void operator=(Base const&);
};
// C++ 03, allow copy only for children
class Base {
public:
protected:
Base(Base const& other) { ... }
Base& operator=(Base const& other) { ...; return *this; }
};
// C++ 11, prevent copy & move
class Base {
public:
Base(Base&&) = delete;
Base(Base const&) = delete;
Base& operator=(Base) = delete;
};
// C++ 11, allow copy & move only for children
class Base {
public:
protected:
Base(Base&&) = default;
Base(Base const&) = default;
Base& operator=(Base) = default;
};