2

Reading StackOverflow Q&A's such as this and this, it would appear that inheriting from STL containers is generally a bad idea. I don't intend to do this in production code; however, I want to know if it will give me a valid quick and dirty test.

In our code, we make heavy use of the STL, and we wish to test how aligning memory to a 64-byte boundary will affect our code's performance. I was planning to test this by writing a simple custom allocator and having a simple class that inherits std::vector with the only change in the class being that the default allocator is my custom allocator and not std::allocator and then simply writing a script to use sed and replace all instances of std::vector with my new class. Using this approach, I will not ever have any pointers carrying through to the base class (all instances of std::vector have been replaced, so any pointers would be of my custom type instead), which appears to be the biggest concern with inheriting from STL. Is this a valid approach? Are there any other easier/safer alternatives? This is a 3 million line code base, so manually changing all instances of std::vector to use the custom allocator would be a very, very, time-consuming task to say the least.

Community
  • 1
  • 1
R_Kapp
  • 2,818
  • 1
  • 18
  • 32

1 Answers1

16

If you have C++11 support, rather than inheritance you could do a templated using statement:

template <class T>
using custom_vector = std::vector<T, custom_allocator<T>>;

Then use your script to sed std::vector to custom_vector.

Sam Cristall
  • 4,328
  • 17
  • 29