mardi 2 avril 2019

C++ how to move object to a nullptr

I am thinking a strange use case where I want to move an object to a nullptr. Maybe I should give an code fragment:

class Objpair {
   public:
      Objpair(Obj&& a, Obj&&b) : first(&a), second(&b) { }
   private:
       Obj* first;
       Obj* second;
};

The problem is that when a and b is out of scope, the first and second pointer will be dangling. If I can move Object a onto the first pointer then there should be no problem of double free and scoping issues. If the member first were declared as Obj not Obj* pointer, then the straight first(std::move(a)) would do the job. I must be doing something wrong here. I am thinking of move instead of copying because I am trying to transfer of control from another object to the current object and improve on performance.

The pointer version is used because I am thinking about polymorphic behavior for the member object.

Aucun commentaire:

Enregistrer un commentaire