简体   繁体   中英

memory leak after clearing vector of shared pointer

I have a vector of shared pointer like this:

vector <shared_ptr<PhotoWidget>> photoWidgets;
PhotoWidget *photoWidget = new PhotoWidget;
photoWidget->setup(widget);
photoWidgets.emplace_back(move(photoWidget));

I need to clear the memory , but I can't find the proper way for doing that, I read similar topics but noting works for me, I used this code so far without any success.

for( auto&& widget : photoWidgets ) {
    widget.reset();
}
vector<shared_ptr<PhotoWidget>>().swap(photoWidgets);
photoWidgets.clear();
photoWidgets.shrink_to_fit();

the PhotoWidget class is:

#include "ofMain.h"
#include "baseWidget.h"
#include "../lib/json.hpp"

using json = nlohmann::json;

class PhotoWidget: public BaseWidget {
public:
    void setup(json config);
    void update();
    void draw();
    void loadNewPhoto(json data);
    void loadDefaultPhoto();

    ofImage image;
    bool defaultPhotoRunning = true;
    uint64_t lastElapsedTimeMillis;
    uint64_t interval;
};    

I found the problem, I change this part:

PhotoWidget *photoWidget = new PhotoWidget;
photoWidget->setup(widget);
photoWidgets.emplace_back(move(photoWidget));

to this, and the problem is solved:

photoWidgets.emplace_back(make_shared<PhotoWidget>());
photoWidgets[widget["ID"]]->setup(widget);

It seems some how creating new pointer in a variable doesn't worked properly in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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