mardi 12 février 2019

How to incorporate smart pointers in class member function for real time allocation?

I'm creating new object pointers at runtime for N cameras using raw pointers. These pointers are created in a class member function and they each service their own thread - I'm not sure if/how to use smart pointers instead of "new" to allocate the object pointers on the heap. I later delete them in the destructor but I would prefer a cleaner memory management approach than using raw pointers.

Both shared and unique pointer seem to destruct at the end of the scope if initialized in the class member function. I also need to determine the number of cameras at runtime.

Currently:

void cameraManager::scanNetwork(){ 
  for(int i=0; i < this->numCameras; ++i){
      auto * cam = new Camera(this->camConfig[i]);
          ....
  }
}

Something along these lines:

void cameraManager::scanNetwork(){ 
  for(int i=0; i < this->numCameras; ++i){
      std::shared_ptr<Camera> cam = std::make_shared<Camera>(new Camera)(this->camConfig[i]);
          ....
  }
}

Ideally, I want these camera pointers to deallocate when the class deallocates - is there a way to "bind" the destructor of a smart pointer to the destructor of another object?

Aucun commentaire:

Enregistrer un commentaire