2015-07-22 36 views
0

我有一个图片类:内存泄漏时的std :: shared_ptr的为std ::矢量

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表示存在内存泄漏。

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

回答

1

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

+0

那么,make_shared会创建一个赋予它的对象的副本? – Kalessar

+0

那么,如果我只操作类中的vector_ptr,那么feature_vector是多余的? – Kalessar

+0

@Kalessar:make_shared创建一个新对象。它正在调用矢量拷贝构造函数。你应该可以使用'std :: move'来调用移动构造函数。但是,从上面的代码看来,'feature_vector'是多余的。 –