I have a Holder object with these three functions
unique_ptr<Object> Holder::remove(string objName){
std::vector<unique_ptr<Object>>::iterator object =
find_if(objects.begin(), objects.end(),
[&](unique_ptr<Object> & obj){ return obj->name() == objName;}
);
objects.erase(std::remove(objects.begin(), objects.end(), *object));
return std::move(*object);
}
vector<unique_ptr<Object>> const& Holder::getContent() const {
return this->objects;
}
void Holder::add(unique_ptr<Object> objPtr) {
this->objects.push_back(move(objPtr));
}
I have wrote a CPPunit test as below:
void HolderTest::removeObject() {
Holder holder("bag");
unique_ptr<Object> ringPtr(new Object("a"));
holder.add(move(ringPtr));
unique_ptr<Object> swordPtr(new Object("b"));
holder.add(move(swordPtr));
holder.remove("a");
vector<unique_ptr<Object>> const& objects = holder.getContent();
CPPUNIT_ASSERT(objects.size() == 1);
}
This test is passing without problem but what is very strange to me is that that if I am adding the below line:
const std::string name = objects[0].get()->name();
CPPUNIT_ASSERT_EQUALS("b", name);
Then the test is crashing without any message. I have written this line in another test without calling remove and it is working without any problem. If I am changing the value of size of vector to two or 0 CPPUNIT_ASSERT(objects.size() == 2); Then the test fails. So It seems that the remove function is keeping one of the unique_ptr but it turns it to a nullptr? Any iea what is the problem?