1

我需要一组不同的类实例(这里:B),它们都共享相同的基类(这里:A)。
实例应存储为指针,因为它们在别处被引用(此处未显示)。
我试过这样:

class A {
public:
  A() {}
};

class B : public A {
  int m_magicValue;
public:
  B() : A() , m_magicValue(4711){}
  int getMagicValue() { return m_magicValue; }
};

class Manager {
  std::vector<A*> m_array;
public:
  Manager() {}
  virtual ~Manager() {
      for( size_t i=0; i<m_array.size(); i++ )
          delete m_array[i];
      m_array.clear();

  }
  void addA( const A& a ) {
    // here A is copied - here the problem occurs
    m_array.push_back( new A(a) );
//    createSomeReferences( m_array.back() );
  }
  A& getA( size_t idx ) {
    return *m_array[idx];
  }
};

int main() {
  B b;
  Manager manager;
  manager.addA(b);
  B& copiedB = (B&) manager.getA(0);
  int magic = copiedB.getMagicValue(); // magic is some random stuff instead of 4711!
  return 0;   
}

Manager 对 B 类一无所知,它只知道 A。
有趣的事情发生在 addA() 中:这里它试图新复制 B 并将指针存储在数组中。
但正如预期的那样,它不能按预期工作;-) 复制B.getMagicValue(); 返回一个随机值。

原因比较清楚:没有使用B的拷贝构造函数,而是使用了A的拷贝构造函数,所以只拷贝了A部分。

所以现在我的问题是:有没有一种好的方法来实现这样的副本,它继承了整个类层次结构,即使只知道基类?

4

1 回答 1

5

您需要一个虚拟的“克隆”函数(有时通俗地称为“虚拟复制构造函数”):

struct A
{
    virtual ~A() { }
    virtual A * clone() const = 0;
};


struct B : A
{
    virtual A * clone() const
    {
        return new B(*this);
    }
};

用法:

void addA(A const & a)
{
    insert(a.clone());
}

但是,使用原始指针非常愚蠢,最好使克隆函数以及容器都键入std::unique_ptr<A>(否则代码几乎相同)。

(您现在可能会问自己,“为什么没有一个版本unique_ptr已经可以进行深度虚拟克隆,也许称为value_ptr<A>?这是一个很好的问题。)

于 2013-06-03T12:37:46.693 回答