繁体   English   中英

智能指针作为多态的类成员

[英]Smart pointers as class members for polymorphism

我是智能指针的新手,如果有人能给我一个暗示,我是否正在处理智能指针作为类成员是否正确,我将非常感激。 更确切地说,我想要实现的解决方案是在类多态的上下文中,理想情况下应该是异常安全的。

给定一个异构对象容器std::vector<shared_ptr<CBase> > my_vector ),添加元素的常用方法是: my_vector.push_back( shared_ptr<CBase>(new CChild(1))) ,以便稍后,可以通过执行以下操作来调用特定派生类的成员函数: my_vector[0]->doSomething()

  1. 我想要实现的是将堆栈对象添加到向量并仍然能够进行多态。 直觉...... 喜欢: CChild<float> obj1(1); my_vector.push_back(obj1) CChild<float> obj1(1); my_vector.push_back(obj1) 为了解决这个问题,我现在使用的是Virtual Constructor IdiomCChild obj1(1); my_vector.push_back(obj1.clone()); CChild obj1(1); my_vector.push_back(obj1.clone());
    请注意,在我的some派生类中,我有创建对象的静态成员函数,例如: CChild<float> obj1 = CChild<float>::initType2(1);

  2. 由于需求问题以及干净的界面,我现在有一个新的类CFoo<T> ,它具有作为数据成员的指向CBase<T>类的智能指针。
    这个想法是,除了包含其他新的私有成员之外,这个类封装/处理派生对象的智能指针,这样我就可以做某事了。 喜欢:
    CFoo<float> myfoo(CChild<float>::initType2(1)); my_vector.push_back(myfoo); 这意味着容器现在是vector<CFoo<T> >类型而不是vector<shared_ptr<CBase> >

在这种情况下,我想知道如何使用smart pointers作为类成员来实现类的构造函数? operator =的实现operator =遵循copy-swap惯用法怎么样? 下面,我对我的班级设计进行了一些说明:

template < typename T >
class CBase{
    public:
        CBase(){};
        virtual ~CBase(){};
        ...
        virtual CBase<T> * clone() const = 0;
        virtual CBase<T> * create() const = 0;
};

template < typename T >
class CChild1 : public CBase{
    public:
        ...
        CChild1<T> * clone() const  { return new CChild1<T>(*this); }
        CChild1<T> * create() const { return new CChild1<T>(); }
        static CChild1 initType1(double, double);
        static CChild1 initType2(int);

};

template < typename T >
struct type{
    typedef std::tr1::shared_ptr<T> shared_ptr;
};

template < typename T >
class CFoo{

    public:

        CFoo();
        CFoo( const CBase<T> &, int = 0 );
        CFoo( const CFoo<T> & );
        void setBasePtr( const CBase<T> & );
        void swap( CFoo<T> & );
        CFoo<T> & operator = ( CFoo<T> );
        ...
        ~CFoo();

    private:

        typename type<CBase<T> >::shared_ptr m_ptrBase;
        int m_nParam;

};

template < typename T >
CFoo<T>::CFoo()
    :m_nParam(0)
// How shall I handle here the "m_ptrBase" class member? e.g point it to NULL?
{

}

template < typename T >
CFoo<T>::CFoo(const CBase<T> & refBase, int nParam)
    :m_ptrBase(refBase.clone()), // Is this initialization exception-safe?
    m_nParam(nParam)
{

}

template < typename T >
CFoo<T>::CFoo(const CFoo<T> & refFoo)
    :m_ptrBase(refFoo.m_ptrBase),
    m_nParam(refFoo.m_nParam)
{

}

template < typename T >
void CFoo<T>::setBasePtr( const CBase<T> & refBase ){
    // ??? I would like to do sth. like: m_ptrBase(refBase.clone())
}

template < typename T >
CFoo<T>::~CFoo(){
    // The memory is going to be freed by the smart pointer itself and therefore
    // the destructor is empty, right?
}

template < typename T >
void CFoo<T>::swap( CFoo<T> & refFoo ){
//does this here makes sense?
    using std::swap;

    swap(m_ptrBase, refFoo.m_ptrBase);
    swap(m_nParam, refFoo.m_nParam);

}

template < typename T >
CFoo<T> & CFoo<T>::operator = ( CFoo<T> copyFoo ){
    copyFoo.swap(*this);
    return (*this);
}

下面是一个我希望直观实现的例子。 首先,我使用包含指向派生类的智能指针的CFoo<float>对象填充容器,此外还有另一个整数类成员(请注意,所有这些只是说明性的)。

std::vector<CFoo<float> > my_bank;
for (int b=0; b < 3; b++){
   float x = b*sqrt(2);
   my_bank.push_back( new CFoo<float>( CChild1<float>::initType2(x), b) );
}

for (double s= 1.0; s<= 8.0; s *= 2.0){
    my_bank.push_back( new CFoo<float>( CChild2<float>::initType2(x), 0) );
 }

一旦,容器被填充,我想做一些操作,调用virtual函数,例如doSomething专门用于每个派生类。

for (int i=0; i < (int)my_bank.size(); i++){
    int b = my_bank[i].m_nParam;
    CBase<float>* myChild = my_bank[i].m_ptrBase;

    myChild->doSomething( param1, param2, param3, ..., b);
}

我真的不知道如何处理这个问题。 我不明白您列出的一半接口要求,因此请考虑这个可能与您的问题无关的实验性答案。

我建议你告诉我我的方法到底缺少什么,我可以修改它。 我现在将省略模板,因为它们似乎与问题无关。

所以,不用多说,最简单的开始使用一个智能指针容器:

#include <vector>
#include <memory>

struct Base
{
  virtual void f();
};

typedef std::shared_ptr<Base> BasePtr;
typedef std::vector<BasePtr> BaseContainer;

struct DerivedA : Base
{
  virtual void f();
  // ...
};

// further derived classes

用法:

int main()
{
  BaseContainer v;
  v.push_back(BasePtr(new DerivedB));
  v.push_back(BasePtr(new DerivedC(true, 'a', Blue)));

  BasePtr x(new DerivedA);
  some_func(x);
  x->foo()
  v.push_back(x);

  v.front()->foo();
}

如果您碰巧在某处有自动对象,则可以插入副本:

DerivedD d = get_some_d();
v.push_back(BasePtr(new DerivedD(d)));

迭代:

for (BaseContainer::const_iterator it = v.begin(), end = v.end(); it != end; ++it)
{
  (*it)->foo();
}

更新:如果要在构建后初始化对象,可以执行以下操作:

{
  DerivedE * p = new DerivedE(x, y, z); 
  p->init(a, b, c);
  v.push_back(BasePtr(p));
}

或者,如果init函数是虚拟的,甚至更简单:

v.push_back(BasePtr(new DerivedE(x, y, z)));
v.back()->init(a, b, c);

第二次更新:以下是派生对象的外观:

struct DerivedCar : Base
{
  enum EType { None = 0, Porsche, Dodge, Toyota };

  DerivedCar(EType t, bool a, unsigned int p)
  : Base(), type(t), automatic_transmission(a), price(p)
  {
    std::cout << "Congratulations, you know own a " << names[type] << "!\n"; }
  }

private:
  EType type;
  bool automatic_transmission;
  unsigned int price;

  static const std::unordered_map<EType, std::string> names; // fill it in elsewhere
};

用法: Base * b = new DerivedCar(DerivedCar::Porsche, true, 2000);

第三次更新:这个是未连接的,只是说明了如何使用查找表来支持switch语句。 假设我们想要基于某个整数使用许多类似的函数(相同的签名):

struct Foo
{
  void do_a();
  void do_b();
  // ...

  void do(int n)
  {
    switch (n) {
      case 2: do_a(); break;
      case 7: do_b(); break;
    }
  }
};

我们可以在查找表中注册所有函数,而不是切换。 这里我假设C ++ 11支持:

struct Foo
{
  // ...
  static const std::map<int, void(Foo::*)()> do_fns;

  void do(int n)
  {
    auto it = do_fns.find(n);
    if (it != do_fns.end()) { (this->**it)(); }
  }
};

const std::map<nt, void(Foo::*)()> Foo::do_fns {
  { 3, &Foo::do_a },
  { 7, &Foo::do_b },
// ...
};

基本上,您将静态代码转换为容器数据 这总是一件好事。 现在这很容易扩展; 您只需在查找映射中添加新函数即可。 无需再次触摸实际的do()代码!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM