开发者

Invoking the copy constructor of a base class for boost pointer containers?

For the below code, when v is copied, the members of Model class do not get copied.

#include <boost/ptr_container/ptr_vector.hpp>
#include <iostream>
using namespace std;

    class SomeNewClass
    {
    public:
       int a;
    };

    class Model
    {
    public:
       int i;
       SomeNewClass* s;//A deep copy won't happen here automatically

       Model() {}
       Model(const Model& m):i(m.i)
       {
        cout<<"Model Copy ctor invoked"<<endl;
       }
    };

    class ModelInherit : public Model
    {
    public:
       int j;

       ModelInherit() {}
       ModelInherit(const ModelInherit& m):j(m.j)
       {
          //i=m.i;//I don't want to copy like this. I want the copy ctor of Model to be invoked
          cout<<"ModelInherit Copy ctor invoked"<<endl;
       }
    };

    int main()
    {
       boost::ptr_vector<ModelInherit> v;
       v.push_back(new ModelInherit);
       v[0].j = 10;
       v[0].i = 20;
       v[0].s = new SomeNewClass();
       v[0].s->a = 99;

       boost::ptr_vector<ModelInherit> v2( v );
       cout<< v2[0].j <<endl;
       cout<< v2[0].i <<endl;
       //cout<< v2[0].s->a <<endl;//segmentation fault
    }

What is important to note is that if you comment out the copy constructor of ModelInherit, then the pointer container automatically copies t开发者_开发技巧he i variable in the Model class. Sad part is that "SomeNewClass* s" does not get copied. No deep copy.

So my questions are:

  • Do you know how to invoke the copy constructor of the Model class in the above code?
  • How do I ensure a deep copy when the pointer container is automatically copying variables so that even the 'a' variable of SomeNewClass gets copied?


(1) To invoke Model copy constructor, change your ModelInherit copy constructor like following:

ModelInherit(const ModelInherit& m): Model(m), j(m.j) {}

(2) Deep copy can be done like this:

Model(const Model& m): i(m.i), s(0)
{
  if(m.s != 0)
    this->s = new SomeNewClass(*(m.s));
  cout<<"Model Copy ctor invoked"<<endl;
}

And declare a copy constructor for SomeNewClass like below:

SomeNewClass(const SomeNewClass &copy) : a(copy.a)
{
  cout<<"SomeNewClass Copy ctor invoked"<<endl;
}

Don't forget to free Model::s in destructor, otherwise it will leak memory:

~Model () { delete this->s; }  // it's ok if s = 0


Invoking base class copy-constructor is easy:

ModelInherit(const ModelInherit& m): Model(m), j(m.j) {}
                                  //^^^^^^^^ note this

Model(m) invokes base class copy-constructor; the parameter m implicitly converts into base class.

In the base class copy-constructor, you've to manually deep-copy m.s.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜