如何实现ICloneable而不邀请将来的对象切片

时间:2019-08-08 04:51:04

标签: c++ object-slicing cloneable

我的问题是关于如何以传统的ICloneable接口的方式实现这种方式,以便在将来的程序员不关注时不会导致意外的对象切片。这是我要检测的一种编程错误的示例(最好在编译时):

#include <stdio.h>

class ICloneable
{
public:
   virtual ICloneable * clone() const = 0;
};

class A : public ICloneable
{
public:
   A() {}
   A(const A & rhs) {}

   virtual ICloneable * clone() const {return new A(*this);}
};

class B : public A
{
public:
   B() {}
   B(const B & rhs) {}

   // Problem, B's programmer forget to add a clone() method here!
};

int main(int, char**)
{
   B b;
   ICloneable * clone = b.clone();  // d'oh!  (clone) points to an A, not a B!
   return 0;
}

如果B(或B的任何其他非抽象子类)未定义自己的clone()方法,C ++中是否有任何方法可以说服编译器发出错误消息?简而言之,是否有任何自动方法可以在运行时检测此错误?

2 个答案:

答案 0 :(得分:1)

前一段时间,我在相同的情况下面临着同样的问题,而没有找到令人满意的解决方案。

再次考虑这一点,我发现可能是一个解决方案(充其量):

#include <iostream>
#include <typeinfo>
#include <typeindex>

class Base { // abstract
  protected:
    Base() = default;
    Base(const Base&) = default;
    Base& operator=(const Base&) = default;
  public:
    virtual ~Base() = default;

    Base* clone() const
    {
      Base *pClone = this->onClone();
      const std::type_info &tiClone = typeid(*pClone);
      const std::type_info &tiThis = typeid(*this);
#if 0 // in production
      assert(std::type_index(tiClone) == type_index(tiThis),
        "Missing overload of onClone()!");
#else // for demo
      if (std::type_index(tiClone) != std::type_index(tiThis)) {
        std::cout << "ERROR: Missing overload of onClone()!\n"
          << "  in " << tiThis.name() << '\n';
      }
#endif // 0
      return pClone;
    }

  protected:
    virtual Base* onClone() const = 0;
};

class Instanceable: public Base {
  public:
    Instanceable() = default;
    Instanceable(const Instanceable&) = default;
    Instanceable& operator=(const Instanceable&) = default;
    virtual ~Instanceable() = default;

  protected:
    virtual Base* onClone() const { return new Instanceable(*this); }
};

class Derived: public Instanceable {
  public:
    Derived() = default;
    Derived(const Derived&) = default;
    Derived& operator=(const Derived&) = default;
    virtual ~Derived() = default;

  protected:
    virtual Base* onClone() const override { return new Derived(*this); }
};

class WrongDerived: public Derived {
  public:
    WrongDerived() = default;
    WrongDerived(const WrongDerived&) = default;
    WrongDerived& operator=(const WrongDerived&) = default;
    virtual ~WrongDerived() = default;

  // override missing
};

class BadDerived: public Derived {
  public:
    BadDerived() = default;
    BadDerived(const BadDerived&) = default;
    BadDerived& operator=(const BadDerived&) = default;
    virtual ~BadDerived() = default;

  // copy/paste error
  protected:
    virtual Base* onClone() const override { return new Derived(*this); }
};

#define DEBUG(...) std::cout << #__VA_ARGS__ << ";\n"; __VA_ARGS__ 

int main()
{
  DEBUG(Instanceable obj1);
  DEBUG(Base *pObj1Clone = obj1.clone());
  DEBUG(std::cout << "-> " << typeid(*pObj1Clone).name() << "\n\n");
  DEBUG(Derived obj2);
  DEBUG(Base *pObj2Clone = obj2.clone());
  DEBUG(std::cout << "-> " << typeid(*pObj2Clone).name() << "\n\n");
  DEBUG(WrongDerived obj3);
  DEBUG(Base *pObj3Clone = obj3.clone());
  DEBUG(std::cout << "-> " << typeid(*pObj3Clone).name() << "\n\n");
  DEBUG(BadDerived obj4);
  DEBUG(Base *pObj4Clone = obj4.clone());
  DEBUG(std::cout << "-> " << typeid(*pObj4Clone).name() << "\n\n");
}

输出:

Instanceable obj1;
Base *pObj1Clone = obj1.clone();
std::cout << "-> " << typeid(*pObj1Clone).name() << '\n';
-> 12Instanceable

Derived obj2;
Base *pObj2Clone = obj2.clone();
std::cout << "-> " << typeid(*pObj2Clone).name() << '\n';
-> 7Derived

WrongDerived obj3;
Base *pObj3Clone = obj3.clone();
Missing overload of onClone()!
ERROR: Missing overload of onClone()!
  in 12WrongDerived
std::cout << "-> " << typeid(*pObj3Clone).name() << '\n';
-> 7Derived

BadDerived obj4;
Base *pObj4Clone = obj4.clone();
Missing overload of onClone()!
ERROR: Missing overload of onClone()!
  in 10BadDerived
std::cout << "-> " << typeid(*pObj4Clone).name() << '\n';
-> 7Derived

Live Demo on coliru

这个技巧实际上很简单:

它不是取代clone()本身,而是用作蹦床virtual onClone()方法中。因此,clone()可以在返回结果之前检查结果的正确性。

这不是编译时检查,而是运行时检查(我认为是第二好的选择)。假设希望至少在开发期间检查/调试开发中的类库的每个类,我都会发现这是相当可靠的。

答案 1 :(得分:0)

不要使A和B继承自IClonable。使用包装器(BluePrint)代替:

"Hello {}".format(

您将不得不稍微修改一下代码,因为这将返回包装的克隆,而不是立即返回要克隆的元素的克隆。再说一次,我不知道您打算如何使用IClonable接口,因此我无法为您完成此示例。