mardi 30 août 2022

How to manage pointer member variable in class?

I need to manage a pointer in a class, here is a demo:

class Shared {
 public:
  Shared(int i) : i_(i) {}
  void call() {}
  int i_;
};

class CreateObj {  // this class create Shared class
 public:
  CreateObj(int i) : s_(std::shared_ptr<Shared>(new Shared(i))) {

  }
  std::shared_ptr<Shared> s_;  // i used shared_ptr, so i don't need delete it
};

class UserObj {  // this class use Shared
 public:
  void SetShared(Shared* s) {  // here is the problem, shall i use shared_ptr, or just use pointer? seems shared_ptr is better, but i think raw pointer is ok? 
    s_ = s;
  }
  void call() {
    s_->call();
  }
  Shared*s_;  // std::shared_ptr<Shared> s_; is another choice, what is the difference?
};

int main() {
  CreateObj cobj(3);
  UserObj uobj;
  uobj.SetShared(cobj.s_);
}

please see the notes in UserShared, i think use raw pointer is also ok, but in this case, could you let me know what is the difference?

Aucun commentaire:

Enregistrer un commentaire