如何将智能指针合并到类成员函数中以进行实时分配?

时间:2019-02-12 20:30:12

标签: class oop c++11 smart-pointers

我正在使用原始指针在运行时为N个摄像机创建新的对象指针。这些指针是在类成员函数中创建的,它们各自服务于自己的线程-我不确定是否/如何使用智能指针而不是“ new”在堆上分配对象指针。后来我在析构函数中将其删除,但是与使用原始指针相比,我更喜欢一种更干净的内存管理方法。

如果在类成员函数中进行初始化,则共享指针和唯一指针似乎都在作用域末尾被破坏。我还需要确定运行时的摄像机数量。

当前:

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

遵循以下原则:

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]);
          ....
  }
}

理想情况下,我希望这些摄像机指针在类取消分配时重新分配-是否有办法将智能指针的析构函数“绑定”到另一个对象的析构函数?

1 个答案:

答案 0 :(得分:1)

关键是将Camera的智能指针与类一起保留在范围内。

从问题中进行以下尝试是正确的主意,但不幸的是,cam在每次迭代时都会被创建和销毁:

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

可以通过将共享指针保留在成员向量中来将Camera保留在范围内。这样,当cameraManager超出范围时,将为相机调用析构函数:

#include <memory>
#include <vector>
#include <array>

struct camConfiguration { };

struct Camera {
    Camera(camConfiguration) {};
};

struct cameraManager {
    int numCameras;
    std::vector<camConfiguration> camConfig;

    std::vector<std::shared_ptr<Camera>> cameras; // will hold the Cameras
    // or, if you only want the cameras to live in the cameraManager, then
    // std::vector<Camera> cameras; // will hold the Cameras without smart pointers

    cameraManager(int numCameras) : numCameras{numCameras}, camConfig(numCameras) {}
    void scanNetwork();
};

void cameraManager::scanNetwork() {
    for (int i = 0; i < this->numCameras; ++i) {
        // each Camera is added to the cameras vector
        cameras.push_back(std::make_shared<Camera>(this->camConfig[i]));
    }
}

int main()
{
    // will hold the Cameras that must outlive the cameraManager
    std::vector<std::shared_ptr<Camera>> cameras_to_keep; 

    {
        cameraManager cm{4};
        cm.scanNetwork();

        cameras_to_keep.push_back(cm.cameras[0]);
        cameras_to_keep.push_back(cm.cameras[3]);
    } // shared pointers in cameraManager are destroyed, i.e. Camera 1 & Camera 2 are destroyed

} 
// remaining Cameras in cameras_to_keep are destroyed

当然,如上面的评论所述,如果您只希望Camera中存在cameraManager个,而只使用std::vector而不使用{{ 1}} s。