Re: STL removal algorithm question
* Victor Bazarov:
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.
That will be hugely inefficient when a MyStruct is copied within the
vector, as happens e.g. when the vector reallocates.
One slightly less inefficient way could be to use boost::shared_ptr to
encapsulate a BSTR (the BSTR type is a pointer).
But, personally I'd encapsulate that vector in a class, because it's
evidently an implementation of something with a very restricted set of
operations, and use an ordinary for loop in the class' destructor.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?