Anne Quinn
Anne Quinn

Reputation: 13002

Erasing from std::list<Value> using a raw pointer to Value?

I have an std::list<Value> that belongs to a managing construct, handing out Value * pointers whenever a factory method is called. These pointers are passed back to the manager when the Value needs to be destroyed. However, I'm unsure how best to use these pointers to find and erase/remove the element.

class ValueManager{
public:

    Value * createValue(ValueDef & def) {
        m_valueList.push_back( Value( def ) );
        return &m_valueList.back();
    }

    void destroyValue(Value * target) {

        // Mystery!  
        // How does one remove/erase a list element
        // with only a pointer to it's value?

    }

private:

    std::list<Value> m_valueList;

};

Both ::erase and ::remove seem ill fit to the task, one takes an iterator instead of a pointer, and the latter takes an entire value, which can't be done because, in this case, there is no acceptable == comparison method between Values, only the pointer can reliably be used to find the target.

My question, is what is the most efficient implementation destroyValue() could take on?

Upvotes: 0

Views: 182

Answers (1)

John Zwinck
John Zwinck

Reputation: 249153

Simple: stop returning raw pointers, and start returning iterators. Then the user who wants to destroy one will pass in the value received when it was created, just like now. And dereferencing will still work as it does with a raw pointer. But erase will also work, and be efficient.

Upvotes: 3

Related Questions