Re: STL removal algorithm question
Dilip wrote:
I have code similar to this in my project:
Note: BSTR is an abomination conjured up some disturbed person in the
COM world. BSTR strings must be allocated/deallocated using the
SysAllocString/SysFreeString Windows APIs.
Noted.
typedef struct tagMyStruct
{
BSTR somestring;
BSTR someotherstring;
} MyStruct;
Please use C++ way of defining types, it's so much easier:
struct MyStruct
{
BSTR somestring;
BSTR someotherstring;
};
vector<MyStruct> my_struct;
over the course of my app, I allocate the BSTRs inside MyStruct and
stuff them into the vector.
Do you allocate those BSTR yourself? Why not give it to MyStruct to
allocate? You know, like, in a constructor, for example...
When the time comes to get rid of them I was wondering if there is a
way to free the memory pointed to by the BSTR's in every MyStruct
instance inside the vector using a _single_ STL algorithm call?
Define the destructor in MyStruct. Make it deallocate those things.
Of course, to follow the Rule of Three, you will need to define the
copy c-tor and the assignment op as well.
After that, a simple destruction of the vector will free up all the
things.
Currently I use a combination of for_each (with a predicate to delete
the BSTRs) followed by a call to my_struct.erase(mystruct.begin(),
mystruct.end()).
OK
There must be a better way to do this, right?
There must be. Dynamic memory management needs to be the responsibility
of the owner of that memory. So, let MyStruct handle its own memory as
it should.
I looked up remove and remove_if, but they don't seem to be right for
my situation...
They are not.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask