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

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

我有一张图片 class :

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();