In the code base I'm working on, it currently has code that does this often:
// In the header:
class Label
{
public:
void ParseText();
private:
Letter* m_myArray;
};
// In the CPP:
void ParseText()
{
delete[] m_myArray;
m_myArray = new Letter[string_length];
// ......
}
Basically every time the string changes in the label, we delete the old set of letter objects and create them all over again. These letter objects are somewhat lightweight, but since this happens often I can't simply use std::vector<Letter>
since each push_back()
would result in a copy. I'd like to avoid the copy too.
Would using boost pool help here? I can imagine doing this (this is pseudocode, since I'm not sure how to use boost pool exactly yet):
// In the header:
class Label
{
public:
void ParseText();
private:
std::vector<Letter*> m_myArray;
boost::object_pool m_pool;
};
// In the CPP:
void ParseText()
{
// Loop through each element in m_myArray and call pool::free
m_myArray.clear();
// Loop each letter and create a new Letter object in the container
for( ... ) {
m_myArray.push_back(m_pool.malloc()); // Not sure how to handle constructor params
}
// ......
}
This would avoid the copy and would avoid doing allocations so often. However, I've lowered the maintainability of the code since there is so much boilerplate involved in adding/deleting items from the vector.
I've thought of using boost::ptr_vector with a custom deleter, but not sure if this helps much. It helps cleanup but I still have to call pool::malloc()
each time I do a push_back.
Using a custom allocator with std::vector doesn't seem to make sense either since it's preallocated anyway and won't shrink in size.
Can anyone help me figure out the "best" solution for this problem?