jeudi 9 mars 2017

std::unique_ptr

Say I want to manage an Object with unique_ptr in a sort of master class. However, I'm in a situation where many other classes need to use this Object. I'm passing Object* to them. I don't think this is a good design, but I can't find a right solution.

class Gadget1 {
  Object* obj_;
 public:
  Object(Object* obj) : obj_(obj) {} 
};

class Gadget2 {
  // .. similar
};

class Worker {
  std::unique_ptr<Object> obj_;
 public:
  void Worker::init() {
    obj_ = std::make_unique<Object>(...);
    createGadget1(obj->get());
    createGadget2(obj->get());
    ...
  }

What'd be a right and safe approach? Should Gadget have unique_ptr<Object>& instead of Object*?

Aucun commentaire:

Enregistrer un commentaire