nim4n
nim4n

Reputation: 1829

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;
};    

Upvotes: 1

Views: 203

Answers (1)

nim4n
nim4n

Reputation: 1829

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.

Upvotes: 2

Related Questions