I have a vector foos
of unique pointers to my resource type Foo
. I would like to delete some of these that satisfy a given condition. How should I do this ?
class Foo
{
public:
int some_num;
Foo(int some_num_) :some_num{ some_num_ }
{}
int getNum()
{
return some_num;
}
};
using FooPtr = std::unique_ptr<Foo>;
using Foos = std::vector<FooPtr>;
int main()
{
Foos foos;
foos.push_back(std::move(std::make_unique<Foo>(30)));
foos.push_back(std::move(std::make_unique<Foo>(35)));
std::vector<int> some_nums = { 35, 30, 25 };
for each (auto& num in some_nums)
{
foos.erase(std::remove_if(foos.begin(), foos.end(),
[&](auto foo) {return num == foo->getNum(); }), foos.end());
}
return 0;
}
It looks like I'm copying the unique_ptr
and so I get the following error,
'std::unique_ptr<Foo,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)': attempting to reference a deleted function
How should I do this ? I will not be using the resource. I don't care about the ownership beyond this point.
The auto
deduction rules will deduce the type to be std::unique_ptr
, forcing a copy. So just change the parameter type of the lambda expression to
[&](const auto& foo) {return num == foo->getNum(); })