c++pointersboostcollectionsptr-vector

boost ptr_vector handling removal "by reference"


My class has a pointer vector:

ptr_vector<Class> vec;

And in some "setup" method adds a few classes to the vector:

void setupOrSomething()
{
    vec.push_back(new Class(...));
    ....
}

Now clients of this class may wish to add their Class objects to this classes list:

void addThingToMyList(Class *cPointer)
{
    vec.push_back(cPointer);
}

And they may wish to remove them by passing the same pointer:

void removeThingFromMyList(Class *cPointer) { ... }

Now if I understand correctly, after reading this answer (https://stackoverflow.com/a/357043/48998), I need to implement that method as follows:

void removeThingFromMyList(Class *cPointer)
{
    vec.release(std::find_if(vec.begin(),vec.end(),CheckPointerValue(cPointer)).release();
}

struct CheckPointerValue
{
     CheckPointerValue(Class* c):cptr(c) {}
     bool operator()(Class const& X)    { return &X == cptr;}
     private:
        Class* cptr;
};

I understand I have to also call release() a second time on the auto_ptr that is returned from the ptr_vector.release().

Am I correct in assuming this will ensure that the caller of this method (RemoveThing...) will retain a valid reference to its Class object and that it will not be deleted? I simply want vec to gain a temporary ownership and then relinquish it.


Solution

  • Yes, they will retain a pointer to a valid instance. Of course they need to know that the pointer refers to a valid instance in the first place AND that a pointer to that instance is stored in the vector. If it's not, you will get undefined behavior and probably a seg fault.