Skip to content

Instantly share code, notes, and snippets.

@slwu89
Last active April 30, 2019 03:19
Show Gist options
  • Save slwu89/d0541d0d72dabb853fb35b66fdd97c5d to your computer and use it in GitHub Desktop.
Save slwu89/d0541d0d72dabb853fb35b66fdd97c5d to your computer and use it in GitHub Desktop.
unique_ptr<widget> in a list, modify them
// Example program
#include <iostream>
#include <string>
#include <list>
#include <algorithm>
#include <memory>
typedef struct widget {
size_t i;
widget(const size_t i_);
~widget();
} widget;
widget::widget(const size_t i_) : i(i_) {
std::cout << "widget " << i << " is born at " << this << std::endl;
};
widget::~widget(){
std::cout << "widget " << i << " is dying at " << this << std::endl;
};
using widget_ptr = std::unique_ptr<widget>;
static std::list<widget_ptr> widget_pop;
void addone2widget(widget_ptr& wd){
wd->i++;
}
int main()
{
widget_pop.emplace_back(std::make_unique<widget>(0));
widget_pop.emplace_back(std::make_unique<widget>(1));
widget_pop.emplace_back(std::make_unique<widget>(2));
widget_pop.emplace_back(std::make_unique<widget>(3));
widget_pop.emplace_back(std::make_unique<widget>(4));
for(auto& w : widget_pop){
addone2widget(w);
}
for(auto& w : widget_pop){
std::cout << "widget " << w->i << " says hi! \n";
}
std::cout << "going ot get rid of some widgets" << std::endl;
auto new_end = std::remove_if(widget_pop.begin(), widget_pop.end(),
[](const widget_ptr& wd)
{ return (wd->i == 2) || (wd->i == 4); });
widget_pop.erase(new_end, widget_pop.end());
for(auto& w : widget_pop){
std::cout << "widget " << w->i << " says hi! \n";
}
std::cout << "done removing" << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment