Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing a unique_ptr of an object from a vector by an attribute value

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?

like image 718
Govan Avatar asked Oct 18 '15 20:10

Govan


1 Answers

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

You derefence the iterator object after it's been invalidated. See Iterator invalidation rules

Move the pointer before the erase, then you'll be fine.

Other notes:

  • it's funny to use removing with a value (instead of just removing the iterator you got). Do you expect the vector to contain duplicates? Actually, strike that: that would make the erase wrong because it always deletes one element.
  • you also do not check that object might be the end() iterator before dereferencing. Another source of Undefined Behaviour
  • consider taking the name by const& for efficiency

Live On Coliru

#include <memory>
#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

struct Object {
    Object(std::string name) : _name(std::move(name)) { }

    std::string const& name() const { return _name; }
  private:
    std::string _name;
};

struct Holder {
    using Ptr = unique_ptr<Object>;

    Ptr remove(string const& objName) {

        auto it = find_if(objects.begin(), objects.end(), [&](Ptr& obj){ return obj->name() == objName; });

        if (it != objects.end()) {
            auto retval = std::move(*it);
            objects.erase(it);
            return std::move(retval);
        }

        return {}; // or handle as error?
    }

    vector<Ptr> const& getContent() const {
        return this->objects;
    }

    void add(Ptr objPtr) {
        this->objects.push_back(move(objPtr));
    }

  private:
    vector<Ptr> objects;
};

int main() {

    Holder h;
    for(auto n: { "aap", "noot", "mies", "broer", "zus", "jet" })
        h.add(std::make_unique<Object>(n));

    h.remove("broer");
    h.remove("zus");

    for (auto& o : h.getContent())
        std::cout << o->name() << "\n";
}

Prints

aap
noot
mies
jet
like image 156
sehe Avatar answered Sep 23 '22 04:09

sehe