使用std::shared_ptr到std::vector时内存泄漏

Memory leak when using std::shared_ptr to std::vector

本文关键字:std 内存 泄漏 vector ptr shared 使用      更新时间:2023-10-16

我有一个图像类:

class Image{
   public:
    Image()
    {
      vector_ptr = std::make_shared<std::vector<Feature>>(feature_vector);
    }
    std::shared_ptr<std::vector<Feature>> calculate_vector()
    {
      // iterates over a space of possible features, calling
      // vector_ptr->push_back(Feature(type, i, j, w, h, value))
      return vector_ptr;
    }
    std::shared_ptr<std::vector<Feature>> get_vector()
    {
      return vector_ptr;
    }
    void clear_vector()
    {
      vector_ptr->clear();
    }
  private:
    std::vector<Feature> feature_vector;
    std::shared_ptr<std::vector<Feature>> vector_ptr;
};

其中特征由:

给出
struct Feature
{
    Feature(int type, int i, int j, int w, int h, double value);
    void print();
    int type;
    int i, j;
    int w, h;
    double value;
};

但是在连续调用calculate_vector()和clear_vector()之后,htop表示存在内存泄漏

如何解决这个问题?(特征向量非常大)

vector_ptrfeature_vector的副本,它不是围绕它的共享包装器。所以如果你想释放feature_vector.clear();的内存,你也需要调用它。