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表示存在內存泄漏。
如何解決此問題? (特徵向量非常大)
那麼,make_shared會創建一個賦予它的對象的副本? – Kalessar
那麼,如果我只操作類中的vector_ptr,那麼feature_vector是多餘的? – Kalessar
@Kalessar:make_shared創建一個新對象。它正在調用矢量拷貝構造函數。你應該可以使用'std :: move'來調用移動構造函數。但是,從上面的代碼看來,'feature_vector'是多餘的。 –