繁体   English   中英

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

[英]Memory leak when using std::shared_ptr to std::vector

我有一个Image类:

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(); 同样,如果您想释放它的内存。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM