How to approach copying objects with smart pointers as class attributes?

后端 未结 5 614
小鲜肉
小鲜肉 2021-01-02 16:15

From the boost library documentation I read this:

Conceptually, smart pointers are seen as owning the object pointed to, and thus responsible for de

5条回答
  •  無奈伤痛
    2021-01-02 16:18

    It sounds like need to be able to make a smart pointer that creates a new copy of the object each time another smart pointer object is created. (Whether that copy is "deep" or not is up to the constructor of the object, I guess; the objects you're storing could have many levels deep of ownership, for all we know, so "deep" depends on the meaning of the objects. The main thing for our purposes is that you want something that creates a distinct object when the smart pointer is constructed with a reference from another one, rather than just taking out a pointer to the existing object.)

    If I've understood the question correctly, then you will require a virtual clone method. There's no other way to call the derived class's constructor correctly.

    struct Clonable {
      virtual ~Clonable() {}
      virtual Clonable* clone() = 0;
    };
    struct AutoPtrClonable {
      AutoPtrClonable(Clonable* cl=0) : obj(cl) { }
      AutoPtrClonable(const AutoPtrClonable& apc) : obj(apc.obj->clone()) { }
      ~AutoPtrClonable() { delete obj; }
      // operator->, operator*, etc
      Clonable* obj;
    };
    

    To use sample code, make it into a template, etc.

提交回复
热议问题